Python内存读写操作示例

yipeiwu_com6年前Python基础

本文实例讲述了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'\xe4\xb8\xad\xe6\x96\x87'

如下图所示:

 

而写入同时也是:

>>> 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'

解决方法为将

from io import StringIO

更换成:

from io import BytesIO as StringIO

即可运行得到正常结果!

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

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

相关文章

pygame实现雷电游戏雏形开发

pygame实现雷电游戏雏形开发

本文实例为大家分享了pygame实现雷电游戏开发代码,供大家参考,具体内容如下 源代码: stars.py #-*- coding=utf-8 -*- #!/usr/bin/pyt...

Python Cookie 读取和保存方法

如下所示: #保存 cookie 到变量 import urllib.request import http.cookiejar cookie = http.cookiejar.Co...

python实现在每个独立进程中运行一个函数的方法

本文实例讲述了python实现在每个独立进程中运行一个函数的方法。分享给大家供大家参考。具体分析如下: 这个简单的函数可以同于在单独的进程中运行另外一个函数,这对于释放内存资源非常有用...

python实现根据月份和日期得到星座的方法

本文实例讲述了python实现根据月份和日期得到星座的方法。分享给大家供大家参考。具体实现方法如下: #计算星座 def Zodiac(month, day): n = (u'摩...

python返回数组的索引实例

使用python里的index nums = [1, 2, 3, 4, 5, 6, 1, 9] print nums.index(max(nums)) print nums.inde...