zoukankan      html  css  js  c++  java
  • Python(00):内存中读写数据StringIO和BytesIO

    流读写

    很多时候,数据读写不一定是文件,也可以在内存中读写。

    1、StringIO:在内存中读写str。

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

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

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

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

    from io import StringIO
    f = StringIO('Hello!
    Hi!
    Goodbye!')
    while True:
            s = f.readline()
            if s == '':
                break
            print(s.strip())
    # Hello! 
    # Hi! 
    # Goodbye!

    2、BytesIO:在内存中读写bytes

    StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO。

    BytesIO实现了在内存中读写bytes,我们创建一个BytesIO,然后写入一些bytes:

    请注意,写入的不是str,而是经过UTF-8编码的bytes。

    from io import BytesIO
    f = BytesIO()
    f.write('中文'.encode('utf-8'))
    print(f.getvalue())  # b'xe4xb8xadxe6x96x87'

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

    from io import BytesIO
    f = BytesIO(b'xe4xb8xadxe6x96x87')
    f.read().decode('utf-8')  # '中文'

    3、小结

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

  • 相关阅读:
    java:产生小数位数为2的随机概率,使得和为1
    大数据网络分析规划
    java碎笔
    mysql修改记录
    mysql导入导出数据
    Centos中hive/hbase/hadoop/mysql实际操作及问题总结
    linux后台运行程序
    Centos搭建mysql/Hadoop/Hive/Hbase/Sqoop/Pig
    ARM-LINUX自动采集温湿度传感器数据
    java中枚举类型的使用
  • 原文地址:https://www.cnblogs.com/springsnow/p/12611566.html
Copyright © 2011-2022 走看看