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

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

示例1:

# -*- 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:

# -*- 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

from io import BytesIO
>>> f = BytesIO()
>>> f.write('中文'.encode('utf-8'))
6
>>> print(f.getvalue())
b'xe4xb8xadxe6x96x87'

如下图所示:

 

python读取windows上的内存 python 读取指定内存_python

而写入同时也是:

>>> from io import BytesIO
>>> f = BytesIO(b'xe4xb8xadxe6x96x87')
>>> f.read()
b'xe4xb8xadxe6x96x87'

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

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

解决方法为将


from io import StringIO


更换成:


from io import BytesIO as StringIO


即可运行得到正常结果!