StringIO的行为与file对象非常像,但它不是磁盘上文件,而是一个内存里的“文件”,我们可以像操作磁盘文件那样来操作StringIO。这篇文章主要介绍了Python StringIO模块,此模块主要用于在内存缓冲区中读写数据。模块中只有一个StringIO类,所以它的可用方法都在类中,此类中的大部分函数都与对文件的操作方法类似。

----------------------------------

s=StringIO.StringIO([buf])
此实例类似于open方法,不同的是它并不会在硬盘中生成文件,而只寄存在缓冲区;可选参数buf是一个str或unicode类型。它将会与其他后续写入的数据存放在一起(注意,若要在初始化数据之后继续写入数据,则在写入数据之前,应先将读写位置移动到结尾,然后再写入,否则,初始化数据会被覆盖掉,因为读写位置默认是0)。

StringIO类中的方法:
s.read([n])
参数n限定读取长度,int类型;缺省状态为从当前读写位置读取对象s中存储的所有数据。读取结束后,读写位置被移动。
----------------------
s.readline([length])
参数length限定读取的结束位置,int类型,缺省状态为None:从当前读写位置读取至下一个以“\n”为结束符的当前行。读写位置被移动。
----------------------
s.readlines([sizehint])
参数sizehint为int类型,缺省状态为读取所有行并作为列表返回,除此之外从当前读写位置读取至下一个以“\n”为结束符的当前行。读写位置被移动。
----------------------
s.write(s)
从读写位置将参数s写入给对象s。参数s为str或unicode类型。读写位置被移动。
----------------------
s.writelines(list)
从读写位置将list写入给对象s。参数list为一个列表,列表的成员为str或unicode类型。读写位置被移动。
----------------------
s.getvalue()
此函数没有参数,无论读写位置在哪里,都能够返回对象s中的所有数据。
----------------------
s.truncate([size])
1》有size参数

无论读写位置在哪里,都从起始位置开始,裁剪size字节的数据。

2》不带size参数

将当前读写位置之前的数据,裁剪下来。
----------------------
s.tell()
返回当前读写位置。
----------------------
s.seek(pos[,mode])
移动当前读写位置至pos处,可选参数mode为0时将读写位置移动至pos处,
为1时将读写位置从当前位置起向前或向后移动|pos|个长度,
为2时将读写位置置于末尾处再向前或向后移动|pos|个长度;

mode的默认值为0。
----------------------
s.close()
释放缓冲区,执行此函数后,数据将被释放,也不可再进行操作。
----------------------
s.isatty()
此函数总是返回0。
----------------------
s.flush()
刷新内部缓冲区。
----------------------

实例1:

  1. def writedata(file, msg):
  2. file.write(msg)
  3. f = open(r'C:\Users\91135\Desktop\test.txt', 'w')
  4. writedata(f, "xxxxx!!!!")
  5. f.close()
  6. f = open(r'C:\Users\91135\Desktop\test.txt', 'r')
  7. print f.read()
  8. f.close()

实例2:

  1. import StringIO
  2. def writedata(file, msg):
  3. file.write(msg)
  4. s = StringIO.StringIO('python')
  5. print s.tell()#读写位置默认是0,因此,之后写入的数据("xxxxx!!!xxxxxx")会将之前的数据('python')覆盖掉
  6. writedata(s, "xxxxx!!!xxxxxx")
  7. print s.getvalue()

实例3:

  1. import StringIO
  2. s = StringIO.StringIO('python')
  3. s.seek(0,2)#将读写位置移动到结尾
  4. s.write("aaaa")
  5. lines = ['xxxxx', 'bbbbbbb']
  6. s.writelines(lines)
  7. s.write("ttttttttt")
  8. print s.getvalue()
  9. #如果使用read方法获取其中的数据,必须通过seek先设置"文件指针"的位置。
  10. s.seek(0,0)#使用s.read()来读取所有数据前,应将读写位置移动到开头
  11. print s.read()
  12. print s.len

实例4:

  1. import StringIO
  2. s = StringIO.StringIO("python")
  3. #读写位置默认是0,下面的语句在写入数据时,并没有移动读写位置,因此,之前的数据("python")会被覆盖掉。
  4. s.write("hello python!")
  5. s.write('hello world!')
  6. s.seek(0)
  7. print s.read()
  8. s.seek(-4,2)#移动读写位置,以便读取最后4个字节
  9. print s.read()

通过例子,我们看到了StringIO的行为,基本与file一致。StringIO提供了一个方法,无论读写位置在哪里,都可以方便的获取其中的数据:StringIO.getvalue()。

Python标准模块中还提供了一个cStringIO模块,它的行为与StringIO基本一致,但运行效率方面比StringIO更好。但使用cStringIO模块时,有几个注意点:
1. cStringIO.StringIO不能作为基类被继承;
2. 创建cStringIO.StringIO对象时,如果初始化函数提供了初始化数据,新生成的对象是只读的。所以下面的代码是错误的:

    1. import cStringIO
    2. s = cStringIO.StringIO("python");
    3. print s
    4. print type(s)
    5. print s.getvalue()
    6. s.write("OOOKKK");#AttributeError: 'cStringIO.StringI' object has no attribute 'write'

练习使用记录:

In [182]: import StringIO

In [183]: s = StringIO.StringIO('this is a test')

In [184]: print s.getvalue()
this is a test

In [185]: s.tell()
Out[185]: 0

In [186]: s.seek(15,1)

In [187]: print s.tell()
15

In [188]: print s.getvalue()
this is a test

In [189]: s.write('this is also a test')

In [190]: print s.read
<bound method StringIO.read of <StringIO.StringIO instance at 0x03F32030>>

In [191]: print s.read()

In [192]: print s.getvalue()
this is a test this is also a test

In [193]: print s.tell()
34

In [194]: print s.seek(10,2)
None

In [195]: s.seek(-10,2)

In [196]: print s.read()
lso a test

In [197]: print s.getvalue
<bound method StringIO.getvalue of <StringIO.StringIO instance at 0x03F32030>>

In [198]: print s.getvalue()
this is a test this is also a test

转发自http://blog.csdn.net/sxingming/article/details/52183563

Python StringIO实现内存缓冲区中读写数据的更多相关文章

  1. StringIO 模块用于在内存缓冲区中读写数据

    模块是用类编写的,只有一个StringIO类,所以它的可用方法都在类中.此类中的大部分函数都与对文件的操作方法类似. 例: #coding=gbk import StringIO s=StringIO ...

  2. 用python批量向数据库(MySQL)中导入数据

    用python批量向数据库(MySQL)中导入数据 现有数十万条数据,如下的经过打乱处理过的数据进行导入 数据库内部的表格的数据格式如下与下面的表格结构相同 Current database: pyt ...

  3. tcp发送缓冲区中的数据都是由产生数据的进程给推送到ip层还是有定时任务触发?

    和几个变量有非常大的关系 发送缓冲区的大小,如何单独设置一个socket的发送缓冲区 socketopt 发送缓冲区中的数据,如果被拥塞窗口限制住了,那么这些数据可能就放在tcpbuffer里的,此时 ...

  4. node.js 从文件流中读写数据及管道流

    读取数据 // 引入 fs 模块 const fs = require('fs'); // 创建可读流 let readStream = fs.createReadStream('index.txt' ...

  5. python从Microsoft Excel文件中导入数据

    excel中后缀为csv和xls,二者区别如下:1.xls 文件就是Microsoft excel电子表格的文件格式.2.csv是最通用的一种文件格式,它可以非常容易地被导入各种PC表格及数据库中. ...

  6. python 读取文本文档中的数据

    import os dir = input('Please input the file dir:')#提示输入文件路径 while not os.path.exists(dir):#判断文件是否存在 ...

  7. pyodbc 向excel中读写数据

    import pyodbc conn_info=( 'DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};''DBQ=[Sh ...

  8. 用python脚本 从xls文件中读取数据

    导入 xlrd 第三方模块 import xlrd data = xlrd.open_workbook('test.xlsx') # 打开xls文件 table = data.sheets()[0] ...

  9. 已经不再使用的表为什么数据页还在SQLServer的内存缓存中

    1. 问题发现 在学习内存调优时,使用如下代码,查询目前内存缓冲区中生产数据库的每个对象缓存页计数 SELECT count(*)AS cached_pages_count ,name ,index_ ...

随机推荐

  1. 并发测试 java.lang.OutOfMemoryError: GC overhead limit exceeded Xms Xmx 阻塞请求 单节点 请求分发 负载均衡

    at javax.servlet.http.HttpServlet.service(HttpServlet.java:705) at javax.servlet.http.HttpServlet.se ...

  2. 服务不支持 chkconfig 的解决方法

    系统服务,在chkconfig --add  servername的时候老是提示服务不支持 chkconfig,经过查找,解决办法如下. 示例,auto_run的前三行如下:#!/bin/sh#chk ...

  3. 原!mysql5.6 存储过程 批量建表

    由于业务需求,需要按天分表,因此写了个存储过程,根据时间生成表. 根据createTime 的时间,以及 while循环的变量设置范围,生成该指定日期及之后的多张表. BEGIN ); ); ; '; ...

  4. git 从远程仓库指定分支clone代码到本地

    不指定分支 git clone + clone 地址 # 例如 git clone https://amc-msra.visualstudio.com/xxx/_xx/xxxxxx 指定分支 git ...

  5. 我的Android进阶之旅------>解决Android Studio编译后安装apk报错:The APK file does not exist on disk

    1.错误描述 今天用Android Studio编译应用后安装APK的时候,报错了,错误如下所示: The APK file build\outputs\apk\OYP_2.3.4_I2Base_64 ...

  6. ThreadLocal 示例

    ThreadLocal, 从字面意思上看是本地线程. 但实际上它是一个线程本地变量.它的功能就是为每一个使用该变量的线程都提供一个变量值的副本, 从而使得不会与其他线程的副本冲突. 与使用synchr ...

  7. BeanUtils.copyProperties()

    BeanUtils.copyProperties() PropertyUtils.copyProperties() 通过反射将一个对象的值赋值个另外一个对象(前提是对象中属性的名字相同). 后付前 P ...

  8. 关于 tf.nn.softmax_cross_entropy_with_logits 及 tf.clip_by_value

    In order to train our model, we need to define what it means for the model to be good. Well, actuall ...

  9. qt下通过socket传送中文

    zz 1.在main函数里我之前就加了一句QTextCodec::setCodecForTr( QTextCodec::codecForLocale() ); 现在再加一句QTextCodec::se ...

  10. CAS单点登录实践(spring cas client配置)

    前言: 最近的项目需要将多个站点统一登录,查阅了资料Jasig cas(Central Authentication Service)(官方站点:http://www.jasig.org/cas)使用 ...