【问题标题】:Append a list of strings to a file in a single line? - Python在一行中将字符串列表附加到文件中? - Python
【发布时间】:2013-07-15 16:25:42
【问题描述】:

有没有办法在一行 python 代码中将行列表附加到文件中?我一直在这样做:

lines = ['this is the foo bar line to append','this is the second line', 'whatever third line']

for l in lines:
  print>>open(infile,'a'), l

【问题讨论】:

    标签: python string file append output


    【解决方案1】:

    两行:

    lines = [ ... ]
    
    with open('sometextfile', 'a') as outfile:
        outfile.write('\n'.join(lines) + '\n')
    

    我们在末尾添加\n 作为尾随换行符。

    一行:

    lines = [ ... ]
    open('sometextfile', 'a').write('\n'.join(lines) + '\n')
    

    不过,我会主张使用第一个。

    【讨论】:

    • 似乎这是我们最接近单线的。
    【解决方案2】:

    你可以这样做:

    lines = ['this is the foo bar line to append','this is the second line', 'whatever third line']
    
    with open('file.txt', 'w') as fd:
        fd.write('\n'.join(lines))
    

    【讨论】:

    • @2er0 如果您需要追加 yes(即如果文件中已经有某些内容),但是使用此解决方案,您一次写入整个缓冲区,所以没关系。
    【解决方案3】:

    不是每次写入都重新打开文件,您可以

    lines = ['this is the foo bar line to append','this is the second line', 'whatever third line']
    
    out = open('filename','a')
    for l in lines:
      out.write(l)
    

    这将把它们写在一个新的行上。如果你想让它们在一行中,你可以

    lines = ['this is the foo bar line to append','this is the second line', 'whatever third line']
    
    out = open('filename','a')
    for l in lines:
      longline = longline + l
    out.write(longline)
    

    您可能还想添加一个空格,如“longline = longline + ' ' + l”。

    【讨论】:

      猜你喜欢
      • 2020-04-15
      • 1970-01-01
      • 2018-09-13
      • 2011-01-04
      • 2019-02-13
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      • 2018-08-30
      相关资源
      最近更新 更多