参考:
廖雪峰python的StringIO模块
python的StringIO模块
本质上就是在内存里操作字符串或者字节嘛,只不过看起来像在操作文件
StringIO
"""
read()等类似文件的接口,使用的时候和文件很像,==光标== 也会移动
而且只能读取初始化时加载的数据,不能读取后面 write 的数据
"""
from io import StringIO
f1 = StringIO()
f1.write("hello")
print(f1.getvalue())
print(f1.read())
print(f1.getvalue())
print("-"*20)
f2 = StringIO("hello world")
print(f2.read())
print(f2.getvalue())
print("read之后")
print(f2.read())
print("read之后")
f2.write("!")
print(f2.read())
print(f2.getvalue())
print("end")
hello
hello
--------------------
hello world
hello world
read之后
read之后
hello world!
end
BytesIO
>>> from io import BytesIO
>>> f = BytesIO()
>>> f.write('中文'.encode('utf-8'))
6
>>> print(f.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'
--------------------------
>>> from io import BytesIO
>>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
>>> f.read()
b'\xe4\xb8\xad\xe6\x96\x87'

本文介绍Python中StringIO和BytesIO模块的使用,演示了如何在内存中读写字符串和字节,类似于文件操作但无需磁盘I/O,适用于高效数据处理。
6507

被折叠的 条评论
为什么被折叠?



