纳速健身

标题: Python2.X的cStringIO和StringIO库的用法和介绍 [打印本页]

作者: awagink    时间: 2020-8-27 07:27
标题: Python2.X的cStringIO和StringIO库的用法和介绍
python3.x的相关功能已经合并到io库,参考下面链接>>>

python3.x中StringIO与BytesIO的介绍与用法
https://www.nasue.com/forum.php? ... 25787&fromuid=1
(出处: 纳速健身)



Python的StringIO库用于实现在内存缓冲区读写文件,看官方对StringIO的介绍,第一句话就是:The module implements file-like class, StingIO, that reads and writes a string buffer(also known as memory files)

cStringIO和StringIO用法相同,速度更快,常常这样使用:


  1. try:
  2.     import cStringIO as StringIO
  3. except ImportError:
  4.     import StringIO
复制代码


>>> output = StringIO.StringIO()
>>> output.write('At that time, I was afraid')
>>> output


<cStringIO.StringO object at 0x7fba35ffaed8>

>>> print output.getvalue()

At that time, I was afraid
>>> output.close()



但cStringIO.StringIO不能作为基类被继承;2. 创建cStringIO.StringIO对象时,如果初始化函数提供了初始化数据,新生成的对象是只读的。

>>> o2 = cStringIO.StringIO('initialization string')
>>> print o2.getvalue()

initialization string

>>> o2.write('write string')

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>








欢迎光临 纳速健身 (https://nasue.com/) Powered by Discuz! X3.4