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
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)从文件对象复制而不使用有限大小的块(用于避免不受控制的内存消耗).
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)
| 归档时间: |
|
| 查看次数: |
24205 次 |
| 最近记录: |