lst = ['hello world', 'hi I am Josh']
我想写两个文件,一个包含lst [0],另一个包含lst [1]。 这样,它不起作用,因为文件被覆盖。
for wd in lst:
with open('hey.txt', 'wb') as f:
f.write(wd)
我该如何修复该代码?
答案 0 :(得分:5)
您需要指定不同的文件名:
lst = ['hello world', 'hi I am Josh']
index = 0
for wd in lst:
with open('hey%s.txt' % index, 'wb') as f:
f.write(wd)
index += 1
这将在hey0.txt中输出“hello world”,在hey1.txt中输出“hi you is Josh”
您可以将事件替换为:
open('hey%s.txt' % index
部分:
open('hey%s.txt' % (index if index else '')
这样你就会得到“hey.txt”和“hey1.txt”(如果它等于0,它就不附加索引)
答案 1 :(得分:3)
您可以切换循环的顺序:
with open('hey.txt', 'wb') as f:
for wd in lst:
f.write(wd)
或者您可以切换到“追加”模式:
for wd in lst:
with open('hey.txt', 'ab') as f:
f.write(wd)
或者一气呵成地写下来:
with open('hey.txt', 'wb') as f:
f.write("\n".join(lst))
或写入两个不同的文件:
for j, wd in enumerate(lst):
with open('hey_%i.txt' % j, 'wb') as f:
f.write(wd)