博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python模块之StringIO
阅读量:2226 次
发布时间:2019-05-09

本文共 815 字,大约阅读时间需要 2 分钟。

转载自:

StringIO经常被用来作为字符串的缓存,应为StringIO有个好处,他的有些接口和文件操作是一致的,也就是说用同样的代码,可以同时当成文件操作或者StringIO操作。比如:

import
 string, os, sys
import
 StringIO
def
 writedata(fd, msg):
    fd.write(msg)
    
=
 open(
'
aaa.txt
'
'
w
'
)
writedata(f, 
"
xxxxxxxxxxxx
"
)
f.close()
=
 StringIO.StringIO()
writedata(s, 
"
xxxxxxxxxxxxxx
"
)

    因为文件对象和StringIO大部分的方法都是一样的,比如read, readline, readlines, write, writelines都是有的,这样,StringIO就可以非常方便的作为"内存文件对象"。

import
 string
import
 StringIO
=
 StringIO.StringIO()
s.write(
"
aaaa
"
)
lines 
=
 [
'
xxxxx
'
'
bbbbbbb
'
]
s.writelines(lines)
s.seek(0)
print
 s.read()
print
 s.getvalue()
s.write(
"
ttttttttt
"
)
s.seek(0)
print
 s.readlines()
print
 s.len

    StringIO还有一个对应的c语言版的实现,它有更好的性能,但是稍有一点点的区别,cStringIO没有len和pos属性。(还有,cStringIO不支持Unicode编码)

转载于:https://www.cnblogs.com/SophiaTang/archive/2012/06/13/2547202.html

你可能感兴趣的文章
HTTP高并发测试
查看>>
数据重生:让神经机器翻译中的不活跃样本“复活”
查看>>
【Java】【28】提高List的removeAll方法的效率
查看>>
【JS】【31】读取json文件
查看>>
OpenSSL源代码学习[转]
查看>>
Spring下载地址
查看>>
google app api相关(商用)
查看>>
linux放音乐cd
查看>>
GridView+存储过程实现'真分页'
查看>>
flask_migrate
查看>>
解决activemq多消费者并发处理
查看>>
UDP连接和TCP连接的异同
查看>>
hibernate 时间段查询
查看>>
java操作cookie 实现两周内自动登录
查看>>
Tomcat 7优化前及优化后的性能对比
查看>>
Java Guava中的函数式编程讲解
查看>>
Eclipse Memory Analyzer 使用技巧
查看>>
tomcat连接超时
查看>>
谈谈编程思想
查看>>
iOS MapKit导航及地理转码辅助类
查看>>