ITPub博客

首页 > IT职业 > IT生活 > python能读写内存吗

python能读写内存吗

IT生活 作者:wjaning 时间:2021-09-11 10:22:08 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'xe4xb8xadxe6x96x87'
#解码:中文
from io import BytesIO
bio2 = BytesIO("中国红".encode("utf-8"))
print(bio2.read().decode("utf-8"))
#结果:中国红

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

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2983/viewspace-2834579/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-06

  • 博文量
    73
  • 访问量
    6473