zoukankan      html  css  js  c++  java
  • StringIO与bytesIO

    数据的读写不一定都是文件,也可能在内存中读写

    StringIO(内存中读写str)

    要把str写入StringIO,先创建一个StringIO,然后,像文件一样写入即可

    from io import StringIO
    f = StringIO()
    f.write('hello')
    f.write('  ')
    f.write('world')
    
    print(f.getvalue)       #hello world

    getvalue()方法用于获得写入后的str

    要读取StringIO,可以用str初始化StringIO.然后,像读文件一样

    from io import StringIO
    f= StringIO('hello!
    hi!
    bye!')
    
    while True:
        s=f.readline()
        if s=='':
            break
        print(s.strip())

    BytesIO(内存中读写二进制数据)

    先创建BytesIO,然后写入数据

    from io import BytesIO
    f = BytesIO()
    f.write('香港中文大学'.encode('utf-8'))
    print(f.getvalue())

    和StringIO类似,可以用一个bytes初始化BytesIO,然后,和文件读取一样

    from io import BytesIO
    f = BytesIO(b'xe9xa6x99xe6xb8xafxe4xb8xadxe6x96x87xe5xa4xa7xe5xadxa6')
    
    print(f.getvalue())
    print(f.read().decode('utf-8'))
    
    
    #b'xe9xa6x99xe6xb8xafxe4xb8xadxe6x96x87xe5xa4xa7xe5xadxa6'
    #香港中文大学

    StringIO和BytesIO时在内存中操作str和bytes的方法,使得读写文件具有一致的接口

  • 相关阅读:
    Minimum Inversion Number
    作业四
    牛客小白月赛18 G Forsaken的三维数点
    The Accomodation of Students HDU
    03-Bootstrap学习
    jquery 单击和双击事件冲突解决方案
    13-JS中的面向对象
    12-关于DOM操作的相关案例
    IO多路复用
    python读取excel文件
  • 原文地址:https://www.cnblogs.com/pdun/p/10825448.html
Copyright © 2011-2022 走看看