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!\nhi!\nbye!')

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'\xe9\xa6\x99\xe6\xb8\xaf\xe4\xb8\xad\xe6\x96\x87\xe5\xa4\xa7\xe5\xad\xa6')

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


#b'\xe9\xa6\x99\xe6\xb8\xaf\xe4\xb8\xad\xe6\x96\x87\xe5\xa4\xa7\xe5\xad\xa6'
#香港中文大学

 

 

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

 

posted @ 2019-05-07 14:51  pdun  阅读(245)  评论(0编辑  收藏  举报