python--StringIO-在内存中读写str

StringIO

很多时候,数据读写不一定是文件,也可以在内存中读写。StringIO就是在内存中读写str

from io import StringIO

f = StringIO()    #创建StringIO对象
i=f.write('hello')  #写入字符串
#返回值:返回字符串个数
i=f.write(' 李明')
str=f.getvalue()  #读取字符串

ff = StringIO('Hello!\nHi!\nGoodbye!')
s = ff.readline()  #读取一行
print(s)

BytesIO 

StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO

BytesIO实现了在内存中读写bytes

猜你喜欢

转载自www.cnblogs.com/liming19680104/p/12150686.html