将StringIO内容写入文件的最佳方法是什么?
如何将一个 StringIO
缓冲区的内容写入文件是最好的方法?
我现在的做法是:
buf = StringIO()
fd = open('file.xml', 'w')
# populate buf
fd.write(buf.getvalue ())
但是这样的话, buf.getvalue()
会复制一份内容吗?
2 个回答
17
Python 3:
from io import StringIO
...
with open('file.xml', mode='w') as f:
print(buf.getvalue(), file=f)
Python 2.x:
from StringIO import StringIO
...
with open('file.xml', mode='w') as f:
f.write(buf.getvalue())
98
with open('file.xml', 'w') as fd:
buf.seek(0)
shutil.copyfileobj(buf, fd)
或者可以用 shutil.copyfileobj(buf, fd, -1)
来从一个文件对象复制内容,这样就不需要分块处理(分块处理是为了避免占用过多内存)。