StringIO与bytesIO

数据的读写不一定都是文件,也可能在内存中读写

StringIO(内存中读写str)

要把str写入StringIO,先创建一个StringIO,然后,像文件一样写入即可

from io import StringIO
f = StringIO()
f.write('hello')
f.write('  ')
f.write('world')

print(f.getvalue)       #hello world

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

要读取StringIO,可以用str初始化StringIO.然后,像读文件一样

from io import StringIO
f= StringIO('hello!
hi!
bye!')

while True:
    s=f.readline()
    if s=='':
        break
    print(s.strip())

BytesIO(内存中读写二进制数据)

先创建BytesIO,然后写入数据

from io import BytesIO
f = BytesIO()
f.write('香港中文大学'.encode('utf-8'))
print(f.getvalue())

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

from io import BytesIO
f = BytesIO(b'xe9xa6x99xe6xb8xafxe4xb8xadxe6x96x87xe5xa4xa7xe5xadxa6')

print(f.getvalue())
print(f.read().decode('utf-8'))


#b'xe9xa6x99xe6xb8xafxe4xb8xadxe6x96x87xe5xa4xa7xe5xadxa6'
#香港中文大学

StringIO和BytesIO时在内存中操作str和bytes的方法,使得读写文件具有一致的接口

原文地址:https://www.cnblogs.com/pdun/p/10825448.html