[关闭]
@bergus 2015-10-23T07:21:52.000000Z 字数 1626 阅读 2154

python中的StringIO模块

python StringIO


此模块主要用于在内存缓冲区中读写数据。模块是用类编写的,只有一个StringIO类,所以它的可用方法都在类中。此类中的大部分函数都与对文件的操作方法类似。

  1. #coding=gbk
  2. import StringIO, cStringIO, sys
  3. s = StringIO.StringIO("JGood is a handsome boy")
  4. s.write("JGood is a handsome boy \r\n")
  5. s.write('okkkk中国')
  6. s.seek(0)
  7. print s.read()
  8. #最后4个字节
  9. s.seek(-4, 2)
  10. print s.read()
  11. #---- 结果 ----
  12. #JGood is a handsome boy
  13. #okkkk中国
  14. #中国
  15. s=StringIO.StrngIO([buf])
  16. #此实例类似于open方法,不同的是它并不会在硬盘中生成文件,而只寄存在缓冲区;可选参数buf是一个str或unicode类型。它将会与其他后续写入的数据存放在一起。
  17. StringIO类中的方法:
  18. ....● read
  19. ....● readline
  20. ....● readlines
  21. ....● write
  22. ....● writelines
  23. ....● getvalue
  24. ....● truncate
  25. ....● tell
  26. ....● seek
  27. ....● close
  28. ....● isatty
  29. ....● flush
  30. ----------------------
  31. s.read([n])
  32. 参数n限定读取长度,int类型;缺省状态为从当前读写位置读取对象s中存储的所有数据。读取结束后,读写位置被移动。
  33. ----------------------
  34. s.readline([length])
  35. 参数length限定读取的结束位置,int类型,缺省状态为None:从当前读写位置读取至下一个以“\n”为结束符的当前行。读写位置被移动。
  36. ----------------------
  37. s.readlines([sizehint])
  38. 参数sizehintint类型,缺省状态为读取所有行并作为列表返回,除此之外从当前读写位置读取至下一个以“\n”为结束符的当前行。读写位置被移动。
  39. ----------------------
  40. s.write(s)
  41. 从读写位置将参数s写入给对象s。参数sstrunicode类型。读写位置被移动。
  42. ----------------------
  43. s.writelines(list)
  44. 从读写位置将list写入给对象s。参数list为一个列表,列表的成员为strunicode类型。读写位置被移动。
  45. ----------------------
  46. s.getvalue()
  47. 此函数没有参数,返回对象s中的所有数据。
  48. ----------------------
  49. s.truncate([size])
  50. 从读写位置起切断数据,参数size限定裁剪长度,缺省值为None
  51. ----------------------
  52. s.tell()
  53. 返回当前读写位置。
  54. ----------------------
  55. s.seek(pos[,mode])
  56. 移动当前读写位置至pos处,可选参数mode0时将读写位置移动至pos处,为1时将读写位置从当前位置起向后移动pos个长度,为2时将读写位置置于末尾处再向后移动pos个长度;默认为0
  57. ----------------------
  58. s.close()
  59. 释放缓冲区,执行此函数后,数据将被释放,也不可再进行操作。
  60. ----------------------
  61. s.isatty()
  62. 此函数总是返回0。不论StringIO对象是否已被close()。
  63. ----------------------
  64. s.flush()
  65. 刷新内部缓冲区。
  66. ----------------------
  67. dir(StringIO.StringIO)的返回值中还包含有一个test函数,不过不用理睬它,它没有任何意义
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注