TheJoker 1911 TheJoker 1911 - 1 month ago 35
Python Question

Python 3.5, trying to copy the content of one file into another by defining a function for it

I don't normally ask for help with assignments, but I was stumbled with a part question and I can't seem to get it right. The question is :


Write a function fcopy() that takes as input two file names (as strings) and copies the
content of the first file into the second.


Now so far, this is what I've managed to come up with:

def fcopy(file1, file2):
os.chdir('C:/Users/HOME/Desktop/Introduction to Computing/Lab/assignments')
open_file_1 = open(file1, 'r')
open_file_2 = open(file2, 'w')
for line in open_file_1:
open_file_2.write(line)
open_file_1.close()
open_file_2.close()
open_file_2 = open(file2, 'r')
for line in open_file_2:
print(line)
open_file_2.close()


I managed to get so far by looking through many resources, and I want to know how to make this work. Thanks

Answer

This should help

def fcopy(file1, file2):
    #os.chdir('C:/Users/HOME/Desktop/Introduction to Computing/Lab/assignments')
    open_file_1 = open(file1, 'r')
    open_file_2 = open(file2, 'w')
    for line in open_file_1:
        open_file_2.write(line)
    open_file_1.close()
    open_file_2.close()
    open_file_2 = open(file2, 'r')
    for line in open_file_2:
        print(line)
    open_file_2.close()
fcopy("infile.txt", "outfile.txt")

Here is another approach

def copy(infile, outfile):
    with open(infile) as file_input:
        with open(outfile, "w") as file_output:
            for line in file_input:
                file_output.write(line)
copy("infile.txt", "outfile.txt")

This approach is better because it guarantees you that outfile will be closed.

Printing content from infile and outfile

def copy(infile, outfile):
    with open(infile) as file_input:
        with open(outfile, "w") as file_output:
            for line in file_input:
                file_output.write(line)



    with open(infile, "r") as file_in:
        print("Infile: ")
        for line2 in file_in:
            print(line2)

    print()

    with open(outfile, "r") as file_out:
        print("Outfile: ")
        for line3 in file_out:
            print(line3)            

copy("infile.txt", "outfile.txt")

I am sure there is more optimized way of doing this but this is the one I could do for now. I will update my answer if I find a better way to do this.