【问题标题】:copying lines from one file to another in python [duplicate]在python中将行从一个文件复制到另一个文件[重复]
【发布时间】:2017-10-20 17:18:46
【问题描述】:

好的,我的课堂作业是编写代码,将每一行从一个文本文件复制到一个新的文本文件。我觉得我把头撞在墙上太多了,我再也看不到我在看什么了。

这是我所拥有的:

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

【问题讨论】:

  • destination_file.writelines(line) => destination_file.write(line)
  • destination_file.writelines(source_file) 没有循环
  • 什么是numbers_file?您从不定义它,也没有使用据称从中读取的值。
  • 您应该使用with 语句而不是手动关闭文件。

标签: python lines copying


【解决方案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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    相关资源
    最近更新 更多