Python StringIO实现内存缓冲区中读写数据
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:
- def writedata(file, msg):
- file.write(msg)
- f = open(r'C:\Users\91135\Desktop\test.txt', 'w')
- writedata(f, "xxxxx!!!!")
- f.close()
- f = open(r'C:\Users\91135\Desktop\test.txt', 'r')
- print f.read()
- f.close()
实例2:
- import StringIO
- def writedata(file, msg):
- file.write(msg)
- s = StringIO.StringIO('python')
- print s.tell()#读写位置默认是0,因此,之后写入的数据("xxxxx!!!xxxxxx")会将之前的数据('python')覆盖掉
- writedata(s, "xxxxx!!!xxxxxx")
- print s.getvalue()
实例3:
- import StringIO
- s = StringIO.StringIO('python')
- s.seek(0,2)#将读写位置移动到结尾
- s.write("aaaa")
- lines = ['xxxxx', 'bbbbbbb']
- s.writelines(lines)
- s.write("ttttttttt")
- print s.getvalue()
- #如果使用read方法获取其中的数据,必须通过seek先设置"文件指针"的位置。
- s.seek(0,0)#使用s.read()来读取所有数据前,应将读写位置移动到开头
- print s.read()
- print s.len
实例4:
- import StringIO
- s = StringIO.StringIO("python")
- #读写位置默认是0,下面的语句在写入数据时,并没有移动读写位置,因此,之前的数据("python")会被覆盖掉。
- s.write("hello python!")
- s.write('hello world!')
- s.seek(0)
- print s.read()
- s.seek(-4,2)#移动读写位置,以便读取最后4个字节
- print s.read()
通过例子,我们看到了StringIO的行为,基本与file一致。StringIO提供了一个方法,无论读写位置在哪里,都可以方便的获取其中的数据:StringIO.getvalue()。
Python标准模块中还提供了一个cStringIO模块,它的行为与StringIO基本一致,但运行效率方面比StringIO更好。但使用cStringIO模块时,有几个注意点:
1. cStringIO.StringIO不能作为基类被继承;
2. 创建cStringIO.StringIO对象时,如果初始化函数提供了初始化数据,新生成的对象是只读的。所以下面的代码是错误的:
- import cStringIO
- s = cStringIO.StringIO("python");
- print s
- print type(s)
- print s.getvalue()
- 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实现内存缓冲区中读写数据的更多相关文章
- StringIO 模块用于在内存缓冲区中读写数据
模块是用类编写的,只有一个StringIO类,所以它的可用方法都在类中.此类中的大部分函数都与对文件的操作方法类似. 例: #coding=gbk import StringIO s=StringIO ...
- 用python批量向数据库(MySQL)中导入数据
用python批量向数据库(MySQL)中导入数据 现有数十万条数据,如下的经过打乱处理过的数据进行导入 数据库内部的表格的数据格式如下与下面的表格结构相同 Current database: pyt ...
- tcp发送缓冲区中的数据都是由产生数据的进程给推送到ip层还是有定时任务触发?
和几个变量有非常大的关系 发送缓冲区的大小,如何单独设置一个socket的发送缓冲区 socketopt 发送缓冲区中的数据,如果被拥塞窗口限制住了,那么这些数据可能就放在tcpbuffer里的,此时 ...
- node.js 从文件流中读写数据及管道流
读取数据 // 引入 fs 模块 const fs = require('fs'); // 创建可读流 let readStream = fs.createReadStream('index.txt' ...
- python从Microsoft Excel文件中导入数据
excel中后缀为csv和xls,二者区别如下:1.xls 文件就是Microsoft excel电子表格的文件格式.2.csv是最通用的一种文件格式,它可以非常容易地被导入各种PC表格及数据库中. ...
- python 读取文本文档中的数据
import os dir = input('Please input the file dir:')#提示输入文件路径 while not os.path.exists(dir):#判断文件是否存在 ...
- pyodbc 向excel中读写数据
import pyodbc conn_info=( 'DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};''DBQ=[Sh ...
- 用python脚本 从xls文件中读取数据
导入 xlrd 第三方模块 import xlrd data = xlrd.open_workbook('test.xlsx') # 打开xls文件 table = data.sheets()[0] ...
- 已经不再使用的表为什么数据页还在SQLServer的内存缓存中
1. 问题发现 在学习内存调优时,使用如下代码,查询目前内存缓冲区中生产数据库的每个对象缓存页计数 SELECT count(*)AS cached_pages_count ,name ,index_ ...
随机推荐
- pre 布局
w
- kafka-docker----(how to setup http proxy in container??)
https://github.com/wurstmeister/kafka-docker environment: KAFKA_ADVERTISED_HOST_NAME: 10.10.160.243 ...
- java 集合类复习(未完结)
JAVA常用数据结构及原理分析(面试总结) https://blog.csdn.net/qq_29631809/article/details/72599708 java 中几种常用数据结构 ht ...
- MTK平台环境搭建---Ubuntu Linux 下执行sudo apt-get install提示“现在没有可用的软件包……
问题描述: sudo apt-get install openssh-server 正在读取软件包列表... 完成正在分析软件包的依赖关系树 Reading state information... ...
- Django 分页器 缓存 信号 序列化
阅读目录 分页器 缓存 信号 序列化 Django分页器 (paginator) 导入 from django.core.paginator import Paginator, EmptyPage, ...
- MySQL 数据类型(Day41)
一.介绍 存储引擎决定了表的类型,而表内存放的数据也要有不同的类型,每种数据类型都有自己的高度,但宽度是可选的. mysql数据类型概览 #1.数字:(默认都是有符号,宽度指的是显示宽度,与存储无关) ...
- numpy.random.seed()
numpy.random.seed():用于指定随机数生成时使用算法的开始值,如果没有指定每次生成的值都不一样 如果不指定seed的值,那么每次随机生成的数字都不一样: In [17]: import ...
- Divide by Zero 2017 and Codeforces Round #399 (Div. 1 + Div. 2, combined) A. Oath of the Night's Watch
地址:http://codeforces.com/problemset/problem/768/A 题目: A. Oath of the Night's Watch time limit per te ...
- kmp模板 && 扩展kmp模板
kmp模板: #include <bits/stdc++.h> #define PB push_back #define MP make_pair using namespace std; ...
- hadoop nn 运维一例
nn1 崩溃之后,nn2变为active,但是nn1日志中有异常,处于standby状态的,无法响应读的操作 最后查出原因是因为fensing的问题.