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
     
    = 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()

    刷新内部缓冲区。

  • 相关阅读:
    二分+RMQ/双端队列/尺取法 HDOJ 5289 Assignment
    思维题 HDOJ 5288 OO’s Sequence
    树形DP Codeforces Round #135 (Div. 2) D. Choosing Capital for Treeland
    最大流增广路(KM算法) HDOJ 1853 Cyclic Tour
    最大流增广路(KM算法) HDOJ 1533 Going Home
    最大流增广路(KM算法) HDOJ 2255 奔小康赚大钱
    Complete the Word CodeForces
    Gadgets for dollars and pounds CodeForces
    Vasya and Basketball CodeForces
    Carries SCU
  • 原文地址:https://www.cnblogs.com/hxiaoli/p/8393363.html
Copyright © 2011-2022 走看看