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的方法,使得读写文件具有一致的接口

  • 相关阅读:
    Mac 删除Openfire
    FMDB使用
    豆瓣restful api 状态和错误码
    豆瓣开放api
    常用文字配色方案
    电商网站参考
    HP后端跨域HEADER头
    PHP统计 图表实现方法
    PHP 全过程教程和测试网
    Ajax技术在购物车中的应用(PHP篇)
  • 原文地址:https://www.cnblogs.com/pdun/p/10825448.html
Copyright © 2011-2022 走看看