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

    刷新内部缓冲区。

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

  • 相关阅读:
    基础才是重中之重~B/S系统中的事件订阅
    将不确定变为确实~请自己搞清楚异常页面的设置方法(网上那些资料说的基本都有问题!)
    基础才是重中之重~延迟初始化
    批量替换sqlserver数据库TEXT字段类型的数据
    12554 A Special "Happy Birthday" Song!!!
    Linux socket 网络编程常用函数总结
    新浪微博Python SDK笔记——发微博(一)
    在Ubuntu上下载、编译和安装Android 4.2 最新内核源代码(Linux Kernel)
    20、SQL Server 数据修改之Update
    19、SQL Server 数据修改之Insert into
  • 原文地址:https://www.cnblogs.com/hdk1993/p/8784527.html
Copyright © 2020-2023  润新知