python读取写入内存方法SringIO,BytesIO

python中不仅仅可以在磁盘中写入文件,还允许直接在内存中直接写入数据:需要借助StringIO和BytesIO来实现:

1、直接操作StringIO

from io import StringIO #载入对象
f=StringIO() #创建变量指向对象
f.write('hello,') #写入数据
f.write('  ')
f.write('world.')
print(f.getvalue()) #依次打印获得的数据

getvalue()的方法用于获取写入的str

2、初始化StringIO

from io import StringIO #载入模块
f=StringIO('hello
world') #初始化String

while True: #创造循环条件
    s=f.readline() #对f指向的对象记性逐行读取
    if s=='': #指定退出循环条件,即读取的行数为空
        break #退出循环
    print(s.strip()) #strip()方法用于移除字符串头尾指定的字符(默认为空格)。

3、使用BytesIO操作二进制数据

from io import BytesIO
f=BytesIO()
f.write('中文'.encode('utf-8'))
print(f.getvalue())
>>> b
'xe4xb8xadxe6x96x87'

和StringIO类似,可以用一个bytes初始化BytesIO,然后,像读文件一样读取。

原文地址:https://www.cnblogs.com/engeng/p/6647219.html