Search code examples
pythonlinescopying

copying lines from one file to another in python


Okay so my class assignment is to write the code to copy each line from one text file to a new text file. I feel like I've beaten my head against the wall too much and just can't see what I'm looking at anymore.

Here is what I have:

source_file = open('data1.txt', 'r')
line = numbers_file.readline()
destination_file = open('data2.txt', 'w')
source_file.seek(0)
for line in source_file:
    destination_file.writelines(line)
source_file.close()
destination_file.close()

Solution

  • # opens original file
    file1 = open("data1.txt" , "r")
    # opens new file
    file2 = open("data2.txt" , "w")
    #for each line in old file
    for line in file1:
    #write that line to the new file
        file2.write(line)
    #close file 1
    file1.close()
    #close file2
    file2.clsoe()