zoukankan      html  css  js  c++  java
  • Python之StringIO和BytesIO

    StringIO

    • io模块中的类  from io import StringIO
    • 内存中,开辟一个文本模式的buffer,可以像文件对象一样操作它
    • 当close方法被调用的时候,这个buffer会被释放
     
    StringIO操作
    getvalue() 获取全部内容。根文件指针没有关系
    >>> from io import StringIO
    >>> # 内存中构建
    >>> sio = StringIO()  # 像文件对象一样操作
    >>> print(sio, sio.readable(), sio.writable(), sio.seekable())
    <_io.StringIO object at 0x0000010B14ECE4C8> True True True
    >>> sio.write("hello,world!")
    12
    >>> sio.seek(0)
    0
    >>> sio.readline()
    'hello,world!'
    >>> sio.getvalue()  # 无视指针,输出全部内容
    'hello,world!'
    >>> sio.close()
    
    优点
    一般来说,磁盘的操作比内存的操作要慢得多,内存足够的情况下,一般的优化思路是少落地,减少磁盘IO的过程,可以大大提高程序的运行效率
     
     

    BytesIO

    • io模块中的类  from io import BytesIO
    • 内存中,开辟一个二进制模式的buffer,可以像文件对象一样操作它
    • 当close方法被调用的时候,这个buffer会被释放
     
    BytesIO操作
    >>> from io import BytesIO
    >>> # 内存中构建
    >>> bio = BytesIO()
    >>> print(bio, bio.readable(), bio.writable(), bio.seekable())
    <_io.BytesIO object at 0x0000010B14ED7EB8> True True True
    >>> bio.write(b"hello,world!)
    12
    >>> bio.seek(0)
    0
    >>> bio.readline()
    b'hello,world!'
    >>> bio.getvalue()  # 无视指针,输出全部内容
    b'hello,world!'
    >>> bio.close()
    

     

    file-like对象

    类文件对象,可以像文件对象一样操作
    socket对象、输入输出对象(stdin、stdout)都是类文件对象
    >>> from sys import stdout
    >>> f = stdout
    >>> print(type(f))
    <class 'ipykernel.iostream.OutStream'>
    >>> f.write("hello,world!")
    hello,world!
    
  • 相关阅读:
    131. Palindrome Partitioning
    130. Surrounded Regions
    129. Sum Root to Leaf Numbers
    128. Longest Consecutive Sequence
    125. Valid Palindrome
    124. Binary Tree Maximum Path Sum
    122. Best Time to Buy and Sell Stock II
    121. Best Time to Buy and Sell Stock
    120. Triangle
    119. Pascal's Triangle II
  • 原文地址:https://www.cnblogs.com/liguanzhen/p/9010962.html
Copyright © 2011-2022 走看看