写一个文件而不用python覆盖?

use*_*806 -1 python text list overwrite

lst = ['hello world', 'hi I am Josh']
Run Code Online (Sandbox Code Playgroud)

我想写两个文件,一个包含lst [0],另一个包含lst [1].这样,它不起作用,因为文件被覆盖.

for wd in lst:
   with open('hey.txt', 'wb') as f:
      f.write(wd)
Run Code Online (Sandbox Code Playgroud)

我该如何修复该代码?

Vin*_*ent 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
Run Code Online (Sandbox Code Playgroud)

这将输出hey0.txt中的"hello world"和hey1.txt中的"hi I'Josh"

您可以将事件替换为:

open('hey%s.txt' % index
Run Code Online (Sandbox Code Playgroud)

部分:

open('hey%s.txt' % (index if index else '')
Run Code Online (Sandbox Code Playgroud)

这样你就会得到"hey.txt"和"hey1.txt"(如果它等于0,它就不附加索引)