如何最佳地将 StringIO
缓冲区的内容写入文件?
我目前的做法类似于:
buf = StringIO()
fd = open('file.xml', 'w')
# populate buf
fd.write(buf.getvalue ())
那么buf.getvalue()
会复制内容吗?
shutil.copyfileobj
方法:with open('file.xml', 'w') as fd:
buf.seek(0)
shutil.copyfileobj(buf, fd)
或使用shutil.copyfileobj(buf, fd, -1)
从文件对象中复制,而不使用有限大小的块(用于避免内存消耗不可控)。
fd.close()
- coonceseanwith
关键字时通常不需要这样做。 - gautehPython 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())
buf.getvalue()
的值。 - gautehshutil.copyfileobj
是最佳解决方案,但这让我感到有些奇怪。 - Demitri
StringIO
对象始终存储在主内存中。如果不想这样,不要使用StringIO
,直接写入文件即可。 - Philippbuf.getvalue()
可能会创建内容的副本。 - gauteh