【发布时间】:2019-11-01 17:45:57
【问题描述】:
如何写入文本文件 python 3?
我想读取每一行并写入 line1 的 outputDoc1.txt ,line1 的 outputDoc2.txt ,line1 的 outputDoc3.txt
line1 = "Alright, I think I understand. Thank you again"
line2 = " just had to use join to separate the data"
line3 = " whether that's desirable or not I suppose is down to the OP"
path = "C:\\Users\\subashini.u\\Desktop\\"
l=["line1","line2","line3"]
count = 0
for txt_file in l:
count += 1
for x in range(count):
with open(path + "outputDoc%s.txt" % x) as output_file:
output_file.write(txt_file)
#shutil.copyfileobj(file_response.raw, output_file)
output_file.close()
【问题讨论】:
-
为什么你在写一行之后关闭文件 a) 和 b) 呢?
with表达式将为您关闭文件。 -
是否有理由需要一次向每个文件写入一行?因为现在您将执行 line1、line1、line1、line2 等。如果不需要,那么我建议您一次将所有行写入每个文件,这样您就不会在每次需要新行时都重新打开文件写出来。
-
当前代码有什么问题,是什么问题?
标签: python