python - 在单行中将字符串列表 append 到文件中? - Python

标签 python string file append output

有没有办法将行列表 append 到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

最佳答案

两行:

lines = [ ... ]

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

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

一行:

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

尽管如此,我还是赞成选择第一个。

关于python - 在单行中将字符串列表 append 到文件中? - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17694340/

相关文章:

python - 对引号进行分组并忽略转义引号

c - printf ("%s") 无法正常工作

自制arrayList中的Coredump

Python 异步回调和生成器

python - Numpy:如何用一维数组索引二维数组?

python - TimedRotatingFileHandler 在具有多实例的 Django 中不能正常工作

string - 在 Excel 的 VBA 中,当字符串包含 '&' 时如何操作页眉/页脚

java - 将字符串放入带有单个字符的数组列表Java

c - 无法在屏幕上打印文件内容

python - 使用 Python 验证保存的文本文件以检查参数是否设置