将StringIO的内容写入文件的最佳方法是什么?

gau*_*teh 31 python file-io stringio

StringIO缓冲区的内容写入文件的最佳方法是什么?

我目前做的事情如下:

buf = StringIO()
fd = open ('file.xml', 'w')
# populate buf
fd.write (buf.getvalue ())
Run Code Online (Sandbox Code Playgroud)

但那么buf.getvalue ()会复制内容吗?

Ste*_*ven 57

使用shutil.copyfileobj:

with open ('file.xml', 'w') as fd:
  buf.seek (0)
  shutil.copyfileobj (buf, fd)
Run Code Online (Sandbox Code Playgroud)

或者shutil.copyfileobj (buf, fd, -1)从文件对象复制而不使用有限大小的块(用于避免不受控制的内存消耗).

  • @cooncesean:使用`with`关键字时不应该这样做. (15认同)

Dem*_*tri 16

Python 3:

from io import StringIO
...
with open('file.xml', mode='w') as f:
    print(buf.getvalue(), file=f)
Run Code Online (Sandbox Code Playgroud)

Python 2.x:

from StringIO import StringIO
...
with open('file.xml', mode='w') as f:
    f.write(buf.getvalue())
Run Code Online (Sandbox Code Playgroud)

  • 这会生成“buf.getvalue()”的副本。 (3认同)
  • mode='w' 对于文本文件(如 file.xml)是可以的,但如果内容不是文本,则应该使用 mode='wb' 写入二进制文件 (2认同)