码迷,mamicode.com
首页 > 其他好文 > 详细

内存数据的读取

时间:2019-12-09 15:28:22      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:读写文件   取数   bytesio   创建   实例   code   get   就是   取数据   

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'\xe4\xb8\xad\xe6\x96\x87'

#读取数据

>>> from io import BytesIO

>>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')

>>> 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!\nHi!\nGoodbye!')     #创建一个带内容的实例

>>> while True:      # while循环

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

...     if s == '':

...         break

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

总结:

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

内存数据的读取

标签:读写文件   取数   bytesio   创建   实例   code   get   就是   取数据   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!