【问题标题】:Write a file without overwriting with python?写一个文件而不用python覆盖?
【发布时间】:2014-03-21 14:31:58
【问题描述】:
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)

如何修复该代码?

【问题讨论】:

  • 为什么可以在同一个位置拥有两个同名的不同文件?想想你想在这里做什么..

标签: python list text overwrite


【解决方案1】:

您需要指定不同的文件名:

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 I'm Josh”

您可以事件替换:

open('hey%s.txt' % index

与:

open('hey%s.txt' % (index if index else '')

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

【讨论】:

  • 非常非常有用!!我不知道“%”方法,它是如何工作的?为什么我们使用 %s?非常感谢!
  • 它将字符串的一部分替换为您传递给它的参数。 iirc, %s 表示“将其用作字符串”(您可以使用此语法进行一些数字格式设置)。就像我写了'hey' + str(index) + '.txt'。这里有更多解释:docs.python.org/2/library/stdtypes.html#string-formatting
【解决方案2】:

您可以切换循环的顺序:

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)

【讨论】:

  • 我在写答案时忘记了“枚举”。我发现它比像我那样声明索引变量更干净:)
猜你喜欢
  • 2014-02-05
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 2012-04-15
  • 2011-05-08
  • 1970-01-01
  • 1970-01-01
  • 2012-06-18
相关资源
最近更新 更多