zoukankan      html  css  js  c++  java
  • python中的StringIO模块

    StringIO经常被用来作为字符串的缓存,应为StringIO有个好处,他的有些接口和文件操作是一致的,也就是说用同样的代码,可以同时当成文件操作或者StringIO操作。

    一、例子

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    import StringIO
     
    s = StringIO.StringIO()
    s.write('www.baidu.com ')
    s.write('news.realsil.com.cn')
    s.seek(0)
    print '*' * 20
    print s.tell()
    print s.read()
     
    print '*' * 20
    print s.tell()
    print s.read()
     
    print '*' * 20
    print s.tell()
    print s.getvalue()
     
    print '*' * 20
    print s.tell()
    s.seek(-4,2)
    print s.read()

    运行结果:

    ********************
    0
    www.baidu.com
    news.realsil.com.cn
    ********************
    34

    ********************
    34
    www.baidu.com
    news.realsil.com.cn
    ********************
    34
    m.cn

    二、StringIO类中的方法:

    1. read
    2. readline
    3. readlines
    4. write
    5. writeline
    6. getvalue
    7. truncate
    8. tell
    9. seek
    10. close
    11. isatty
    12. flush

    ----------------------

    s.read([n])

    参数n限定读取长度,int类型;缺省状态为从当前读写位置读取对象s中存储的所有数据。读取结束后,读写位置被移动。

    ----------------------

    s.readline([length])

    参数length限定读取的结束位置,int类型,缺省状态为None:从当前读写位置读取至下一个以“ ”为结束符的当前行。读写位置被移动。

    ----------------------

    s.readlines([sizehint])

    参数sizehint为int类型,缺省状态为读取所有行并作为列表返回,除此之外从当前读写位置读取至下一个以“ ”为结束符的当前行。读写位置被移动。

    ----------------------

    s.write(s)

    从读写位置将参数s写入给对象s。参数s为str或unicode类型。读写位置被移动。

    ----------------------

    s.writelines(list)

    从读写位置将list写入给对象s。参数list为一个列表,列表的成员为str或unicode类型。读写位置被移动。

    ----------------------

    s.getvalue()

    此函数没有参数,返回对象s中的所有数据。

    ----------------------

    s.truncate([size])

    从读写位置起切断数据,参数size限定裁剪长度,缺省值为None。

    ----------------------

    s.tell()

    返回当前读写位置。

    ----------------------

    s.seek(pos[,mode])

    移动当前读写位置至pos处,可选参数mode为0时将读写位置移动至pos处,为1时将读写位置从当前位置起向后移动pos个长度,为2时将读写位置置于末尾处再向后移动pos个长度;默认为0。

    ----------------------

    s.close()

    释放缓冲区,执行此函数后,数据将被释放,也不可再进行操作。

    ----------------------

    s.isatty()

    此函数总是返回0。不论StringIO对象是否已被close()。

    ----------------------

    s.flush()

    刷新内部缓冲区。

    ----------------------

  • 相关阅读:
    【转】Aspose.Cells读取excel文件
    sencha treestore 取消自动加载数据
    百度地图js根据经纬度定位和拖动定位点
    sencha gridpanel checkbox 复选框的勾选 以及和单机行冲突
    c# tcp备忘及networkstream.length此流不支持查找解决
    小程序view排版
    .net+mvc,ueditor
    爬虫BS4—淘女郎
    爬虫手动流程
    python web cgi
  • 原文地址:https://www.cnblogs.com/hdk1993/p/8784527.html
Copyright © 2011-2022 走看看