将StringIO
缓冲区的内容写入文件的最佳方式是什么?
我目前做的事情如下:
buf = StringIO()
fd = open('file.xml', 'w')
# populate buf
fd.write(buf.getvalue ())
但是buf.getvalue()
会复制里面的内容吗?
发布于 2010-07-15 08:36:23
with open('file.xml', 'w') as fd:
buf.seek(0)
shutil.copyfileobj(buf, fd)
或者使用shutil.copyfileobj(buf, fd, -1)
从文件对象复制,而不使用大小有限的块(用于避免不受控制的内存消耗)。
发布于 2019-10-28 18:22:49
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())
https://stackoverflow.com/questions/3253258
复制相似问题