如何写入文本文件python 3?
如何写入文本文件python 3 我想读取每一行,并对line1写入outputDoc1.txt,对line1写入outputDoc2.txt,对line1写入outputDoc3.txt如何写入文本文件python 3?,python,Python,如何写入文本文件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 s
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()
“文件打开”中缺少
write
属性,它引用的是字符串而不是行元素:
换衣服
循环到:
l=[line1,line2,line3]
计数=0
对于l中的txt_文件:
打印(txt_文件)
计数+=1
打开(路径+“outputDoc%s.txt”%count,'w')作为输出文件:
输出文件。写入(txt文件+'\n')
它写道:
/outputDoc1.txt中的第1行
/outputDoc2.txt中的第2行
etc首先,您当前没有写出所需的行
改变
l=["line1","line2","line3"]
到
然后,为了让事情变得简单一点,你可以这样做:
for i, line in enumerate(l, start=1):
...
要打开文件并写入内容,您需要使用正确的模式打开它。open()
的默认模式是read
,因此当前无法写入文件
with open('file', 'w') as f:
...
# no f.close() needed here
为什么要在写了一行之后关闭文件a)和b)呢?带有
表达式的将为您关闭文件。是否有需要每次为每个文件写入一行的原因?因为现在您将执行第1行、第1行、第1行、第2行等操作。如果不需要这样做,那么我建议将所有行同时写入每个文件,这样您就不会在每次需要写入新行时重新打开文件。当前代码有什么问题,问题是什么?正如你所说的,它只是将第3行写入所有文件,因为你使用的是一个范围循环,直到循环列表中的最后一个元素,请尝试我所编辑的
for i, line in enumerate(l, start=1):
...
with open('file', 'w') as f:
...
# no f.close() needed here