Python中的StringIO与cStringIO简析

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">python中的StringIO与cStringIO</span>


StringIO与cStringIO类似,都是向内存中写入文件,其操作与文件操作类似(不敢说相同,但是至少读写是一样的)。一StringIO为例如下:
  1. import StringIO
  2. a = StringIO.StringIO( 'title')
  3. a.write( 'content1\n')
  4. a.write( 'content2')
  5. a.seek( 0) #必须指定文件指针位置到文件开头,否则无法读出数据
  6. print a.read()
  7. a.close() #必须和文件一样关闭
输出结果是:
content1
content2
为什么title没有了呢?
因为实例化一个StringIO之后,文件指针是在文件开头的,也就是指向‘title’开头的位置,之后写入的‘conttent1’将其覆盖了而已。
如果不想让’title‘被覆盖,那么需要将文件指针移动到’title‘末尾,即利用a.seek()函数。
但是这里StringIO文件类似一个列表,和文件操作不一样,a.seek(2)不代表文件末尾,而代表写入参数的第三个字符的位置,即’title‘中第二个’t'的位置。
或者,直接实例化一个空的StringIO,然后再写入内容,一切烦恼就都没有了。


cStringIO不同之处在于,如果实例化一个带有默认数据的cStringIO.StringIO类。那么该实例是read-only的:
  1. import StringIO
  2. a = cStringIO.StringIO( 'title')
  3. a.write( 'content1\n')


返回AttributeError: 'cstringIO.StringI' object has no attribute ‘write’


但是如果实例化时不提供默认参数,那么则是可以读写的。注意到

  1. import cStringIO, StringIO
  2. a = StringIO.StringIO()
  3. b = StringIO.StringIO( 'a')
  4. c = cStringIO.StringIO()
  5. d = cStringIO.StringIO( 'a')
  6. print type(a)
  7. print type(b)
  8. print type(c)
  9. print type(d)
  10. print a.__class__
  11. print b.__class__
  12. print c.__class__
  13. print d.__class__

返回: <type instance>
<type instance>
<type cStringIO.StringO>
<type cStringIO.StringI>
<class StringIO.StringIO at XXXX>
<class StringIO.StringIO at XXXX>
<type cStringIO.StringO>
<type cStringIO.StringI>
但是说明带默认参数的 cStringIO.StringIO生成的是cStringIO.StringIO,它是read-only的,无默认参数的是cStringIO.StringIO,它是可读写的。

猜你喜欢

转载自blog.csdn.net/likunshan/article/details/80899614
今日推荐