内存数据的读取

python : StringIO 和 BytesIO:

--数据读写不一定是文件,也可以在内存中读写

StringIO:

顾名思义就是在内存中读写str。


from io import StringIO
f= StringIO()
f.write('')  # 写入

---》f.getvalue()   #获取写入的数据(str)


--StringIO操作的只能是str!!
--读取StringIO,用一个str初始化StringIO,像读文件一样读取

BytesIO:

要操作二进制数据,就需要使用BytesIO

BytesIO实现了在内存中读写bytes

>>> from io import BytesIO

>>> f = BytesIO()

>>> f.write('中文'.encode('utf-8'))

6

>>> print(f.getvalue())

b'xe4xb8xadxe6x96x87'

#读取数据

>>> from io import BytesIO

>>> f = BytesIO(b'xe4xb8xadxe6x96x87')

>>> f.read()  # 只能读一次,再读为空。 可以把f.read()赋给某个变量,然后解码变量,显示值

#样式一:
>>> from io import StringIO   #  导入StringIO类

>>> f = StringIO()     # 创建一个实例,赋给f对象

>>> f.write('hello')    #  往 f 中写入

5

>>> f.write(' ')

1

>>> f.write('world!')

6

>>> print(f.getvalue())  #getvalue()方法用于获得写入后的str

hello world!

#样式二:
>>> from io import StringIO

>>> f = StringIO('Hello!
Hi!
Goodbye!')     #创建一个带内容的实例

>>> while True:      # while循环

...     s = f.readline()  # 按行读取内容

...     if s == '':

...         break

...     print(s.strip())   # strip(),删除行首行尾的空格

总结:

StringIO和BytesIO是在内存中操作str和bytes的方法,使得和读写文件具有一致的接口。

原文地址:https://www.cnblogs.com/shaozheng/p/12011225.html