在python中将行从一个文件复制到另一个文件

时间:2017-10-20 17:18:47

标签: python lines copying

好的,所以我的类分配是编写代码,将每行从一个文本文件复制到一个新的文本文件。我觉得我已经把头撞到墙上太多了,只是看不到我正在看的东西了。

这就是我所拥有的:

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()

1 个答案:

答案 0 :(得分:1)

# 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()