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

2024-05-23 13:57:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我现在做的事情是:

buf = StringIO()
fd = open ('file.xml', 'w')
# populate buf
fd.write (buf.getvalue ())

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


Tags: 文件方法内容xmlopen事情filewrite
2条回答

Python3:

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

Python2.x:

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

使用shutil.copyfileobj

with open ('file.xml', 'w') as fd:
  buf.seek (0)
  shutil.copyfileobj (buf, fd)

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

相关问题 更多 >