python io StringIO BytesIO 向字内存符串写入数据

创建日期: 2023-06-18 12:47 | 作者: 风波 | 浏览次数: 15 | 分类: Python

来源:https://ironpython-test.readthedocs.io/en/latest/library/stringio.html

像写文件一样写入内存

Python3 代码如下

from io import StringIO

output = StringIO()
output.write('First line.\n')
print >>output, 'Second line.'

# Retrieve file contents -- this will be
# 'First line.\nSecond line.\n'
contents = output.getvalue()

# Close object and discard memory buffer --
# .getvalue() will now raise an exception.
output.close()

注意⚠️:Python2 中的导入和使用方式

import StringIO

output = StringIO.StringIO()
15 浏览
13 爬虫
0 评论