StringIO

要把 str 字符串写入内存中,我们需要创建一个 StringIO 对象,然后像文件一样对读取内容。其中 StringIO 中多了一个 getvalue() 方法,目的是用于获取写入后的 str。

# 定义一个 StringIO 对象,写入并读取其在内存中的内容
from io import StringIO

f = StringIO()

f.write('Python-100')
str = f.getvalue()
print('写入内存中的字符串为:%s' %str)

f.write('\n') # 追加写入内容
f.write('坚持100天')
str = f.getvalue()  # getvalue() 可以读取到 StringIO 中的所有内容
print('写入内存中的字符串为:\n%s' %str)

f.close() # 释放内存中的数据,后续不可再对该 StringIO 进行内容的读写操作

# 输出结果
# 写入内存中的字符串为:
# Python-100
# 写入内存中的字符串为:
# Python-100
# 坚持100天

 

BytesIO

# 定义一个 BytesIO 对象,写入并读取其在内存中的内容

from io import BytesIO

str = 'Python-100' + '\n' + '坚持100天'

f = BytesIO(str.encode('utf-8'))

print('写入内存的字节为:%s' %f.getvalue())

print('字节解码后内容为:\n%s' %f.getvalue().decode('utf-8'))

  

 

 posted on 2023-01-16 16:34  boye169  阅读(40)  评论(0编辑  收藏  举报