脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python内存读写操作示例

Python内存读写操作示例

2021-03-18 00:49笨鸟可以先飞呀 Python

这篇文章主要介绍了Python内存读写操作,结合实例形式分析了Python常见内存读写操作使用方法及相关注意事项,需要的朋友可以参考下

本文实例讲述了Python内存读写操作。分享给大家供大家参考,具体如下:

Python中的读写不一定只是文件,还有可能是内存,所以下面实在内存中的读写操作

示例1:

?
1
2
3
4
5
6
7
8
# -*- coding:utf-8 -*-
#! python3
from io import StringIO
f=StringIO()
f.write('everything')
f.write('is')
f.write('possible')
print(f.getvalue())

运行结果:

everythingispossible

在内存中新建一个StringIO,然后进行写入

获取的时候用的是getvalue()函数

而读取的时候可以用一个循环判断,比如:

示例2:

?
1
2
3
4
5
6
7
8
# -*- coding:utf-8 -*-
#! python3
f=StringIO('everything is possible')
while True:
  s=f.readline()
  if s=='':
    break
  print(s.strip())

运行结果:

everything is possible

同理,可以操作不只是str,还可以是二进制数据,所以会用到BytesIO

?
1
2
3
4
5
6
from io import BytesIO
>>> f = BytesIO()
>>> f.write('中文'.encode('utf-8'))
6
>>> print(f.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'

如下图所示:

 Python内存读写操作示例

而写入同时也是:

?
1
2
3
4
>>> from io import BytesIO
>>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
>>> f.read()
b'\xe4\xb8\xad\xe6\x96\x87'

注:这里的测试环境为Python3,如果使用Python2运行上述示例1的话会提示如下错误:

Traceback (most recent call last):
  File "C:\py\jb51PyDemo\src\Demo\strIODemo.py", line 5, in <module>
    f.write('everything')
TypeError: unicode argument expected, got 'str'

解决方法为将

?
1
from io import StringIO

更换成:

?
1
from io import BytesIO as StringIO

即可运行得到正常结果!

希望本文所述对大家Python程序设计有所帮助。

原文链接:https://blog.csdn.net/xu_weijie/article/details/80763634

延伸 · 阅读

精彩推荐