什么IO?
I/O操作就是在内存上写读(输入输出)的意思。
一、StringIO
StringIO就是在内存上读写str。
1.1写入-平常咱们常用的写入
f = open(file,‘w‘)
f.write(data)
1.2写入-内存中的写入
而内存写入数据,类似与此
from io import StringIO
fi = StringIO()
fi.write(‘write StringIO‘)
#获取fi的值
print(fi.getvalue())
write StringIO
1.3读取-咱们常用的读取
读取StringIO,跟平常咱们用的类似。先看下平常咱们的读取
f = open(file,‘r‘)
f.read()
1.4读取-内存中的读取
在内存中读取stringIO,如下
from io import StringIO
fo = StringIO(‘read StringIO‘)
print(fo.read())
read StringIO
二、BytesIO
和StringIO类似,这里在内存上读写的是二进制数据。BytesIO
from io import BytesIO
#写入
fbi = BytesIO()
fbi.write(b‘write bytesIO‘)
print(fbi.getvalue())
b‘write bytesIO‘
#读取
fbo = BytesIO(b‘read bytesIO‘)
print(fbo.read())
b‘read bytesIO‘
原文:https://blog.51cto.com/15069487/2581974