品易云推流 关闭
文章详情页
文章 > Python常见问题 > python能读写内存吗

python能读写内存吗

头像

silencement

2020-02-06 16:46:172296浏览 · 0收藏 · 0评论

Python内存中的读取与写入

1、内存中的读写-StirngIO

StirngIO顾名思义就是在内存中读写str字符串

sio.write(str)

功能:将字符串写入sio对象中。

sio.getvalue()

功能:获取写入的内容

from io import StringIO#
sio = StringIO()
sio.write("hello")
sio.write("good")
print(sio.getvalue())
#结果:hellogood

sio2.read()
功能:一次性读取所有的sio对象中的内容

from io import StringIO#
sio2 = StringIO("hello jerry!!!")
print(sio2.read())
#结果:hello jerry!!!

2、在内存中读取二进制字符串-BytesIO

StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO,BytesIO实现了在内存中读写bytes。

与StringIO操作类似,但是注意要进行编码写入bytes

from io import BytesIO
f = BytesIO()
f.write("中文".encode('utf-8'))#写入的不是str,而是经过UTF-8编码的bytes
print(f.getvalue())#未解码
print(f.getvalue().decode("utf-8"))#解码

#结果
#未解码:b'\xe4\xb8\xad\xe6\x96\x87'
#解码:中文
from io import BytesIO
bio2 = BytesIO("中国红".encode("utf-8"))
print(bio2.read().decode("utf-8"))
#结果:中国红

更多学习内容,请点击Python学习网!

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图