11

Python标准库: StringIO模块——内存文件

 3 years ago
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.
neoserver,ios ssh client

Python标准库: StringIO模块——内存文件

May 30, 2018

工具, Python

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模块时,有几个注意点:

  1. cStringIO.StringIO不能作为基类被继承
  2. 创建cStringIO.StringIO对象时,如果初始化函数提供了初始化数据,新生成的对象是只读的。所以下面的代码是错误的:
s = cStringIO.StringIO("JGood/n")
s.write("OOOKKK")

</article


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK