总目录:https://blog.csdn.net/qq_41106844/article/details/105553392
Python - 子目录:https://blog.csdn.net/qq_41106844/article/details/105553333
如果我们希望有一些信息,不存在磁盘中,在内存中就将它完成,最后再存到磁盘内。
我们就需要StringIO和BytesIO了。
StringIO
我们来看一个实例
from ioimport StringIO
f = StringIO()
f.write('hello')
f.write(' ')
f.write('world!')
print(f.getvalue())
hello world!
f1 = StringIO('Hello!\nHi!\nGoodbye!')
print(f1.getvalue())
Hello!
Hi!
Goodbye!
方法很简单,我们只需要先创建一个StringIO,之后就可以写入一下信息,最后使用getvalue()就可以获取到内部的信息。
我们可以在创建时直接写入,也可以先创建好后一步一步写。
BytesIO
StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO。
其他地方和StringIO差不多。
from ioimport BytesIO
f1 = BytesIO()
f1.write('中文'.encode('utf-8'))
print(f1.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'
f2 = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
print(f2.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'