首页 > 其他分享 >StringIO 和 BytesIO

StringIO 和 BytesIO

时间:2023-01-16 16:46:31浏览次数:28  
标签:StringIO 写入 getvalue 内存 str 100 BytesIO

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'))

  

 

标签:StringIO,写入,getvalue,内存,str,100,BytesIO
From: https://www.cnblogs.com/boye169/p/17055773.html

相关文章

  • HTMLTestRunner.py引用报错(StringIO)
    报错原因:Python3已将stringIO归入io,但下载的文件未修改解决办法:修改HTMLTestRunner.py文件1.第94行:importStringIO  ===>  importio2.第539行,self.output......
  • ModuleNotFoundError: No module named 'StringIO'
    ModuleNotFoundError:Nomodulenamed'StringIO' 问题描述importStringIO时报错:ModuleNotFoundError:Nomodulenamed'StringIO'。 问题原因Python2.x的写法......