
11

Python标准库: StringIO模块——内存文件
source link: https://sineatos.github.io/tools/programme-language/python/stdlib/stringio/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Python标准库: StringIO模块——内存文件
StringIO的行为与file对象非常像,但它不是磁盘上文件,而是一个内存里的“文件”,我们可以将操作磁盘文件那样来操作StringIO。
一个简单的例子:
import StringIO, cStringIO, sys
s = StringIO.StringIO("JGood is a handsome boy")
s.write("JGood is a handsome boy /r/n")
s.write('okkkk中国')
s.seek(0)
print(s.read())
#最后4个字节
s.seek(-4, 2)
print(s.read())
#---- 结果 ----
#JGood is a handsome boy
#okkkk中国
#中国
通过例子,我们看到了StringIO的行为,基本与file一致。
StringIO.getvalue()
StringIO提供的一个方法,可以方便的获取其中的数据。
如果使用read
方法获取其中的数据,必须通过seek
先设置”文件指针”的位置。
Python标准模块中还提供了一个cStringIO
模块,它的行为与StringIO
基本一致,但运行效率方面比StringIO
更好。但使用cStringIO
模块时,有几个注意点:
- cStringIO.StringIO不能作为基类被继承
- 创建cStringIO.StringIO对象时,如果初始化函数提供了初始化数据,新生成的对象是只读的。所以下面的代码是错误的:
s = cStringIO.StringIO("JGood/n")
s.write("OOOKKK")
</article
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK