介绍一下Python在内存中读写数据,用到的模块是StringIO和BytesIO
StringIO> from io import StringIO
> f = StringIO()
> f.write('hello')
5
> f.write(' ')
1
> f.write('world!')
6
> print(f.getvalue())
hello world!
getvalue()方法用于获得写入后的str。
要读取StringIO,可以用一个str初始化StringIO,然后,像读文件一样读取:> from io import StringIO
> f = StringIO('Hello!\nHi!\nGoodbye!')
> while True:
... s = f.readline()
... if s == '':
... break
... print(s.strip())
...
Hello!
Hi!
Goodbye!
BytesIO
StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO。
BytesIO实现了在内存中读写bytes,我们创建一个BytesIO,然后写入一些bytes:> from io import BytesIO
> f = Bytes