python能读写内存吗

图片[1]-python能读写内存吗-uusu优素-乐高,模型,3d打印,编程

Python内存中的读取与写入

1、内存中的读写-StirngIO

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

sio.write(str)

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

sio.getvalue()

功能:获取写入的内容

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

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

fromioimportStringIO#
sio2=StringIO("hellojerry!!!")
print(sio2.read())
#结果:hellojerry!!!

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

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

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

fromioimportBytesIO
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'
#解码:中文
fromioimportBytesIO
bio2=BytesIO("中国红".encode("utf-8"))
print(bio2.read().decode("utf-8"))
#结果:中国红
原文来自:https://www.py.cn
© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容