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

    StringIO

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

    StringIO顾名思义就是在内存中读写str。

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

    >>> from io import StringIO
    >>> f = StringIO()
    >>> f.write('hello')
    5
    >>> f.write(' ')
    1
    >>> f.write('world!')
    6
    >>> print(f.getvalue())
    hello world!

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

    要读取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!

    BytesIO

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

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

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

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

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

    >>> from io import BytesIO
    >>> f = BytesIO(b'xe4xb8xadxe6x96x87')
    >>> f.read()
    b'xe4xb8xadxe6x96x87'

    小结

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

    参考源码

    do_stringio.py

    do_bytesio.py

    StringIO

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

    StringIO顾名思义就是在内存中读写str。

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

    >>> from io import StringIO
    >>> f = StringIO()
    >>> f.write('hello')
    5
    >>> f.write(' ')
    1
    >>> f.write('world!')
    6
    >>> print(f.getvalue())
    hello world!
    

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

    要读取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!
    

    BytesIO

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

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

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

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

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

    >>> from io import BytesIO
    >>> f = BytesIO(b'xe4xb8xadxe6x96x87')
    >>> f.read()
    b'xe4xb8xadxe6x96x87'
    

    小结

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

    参考源码

    do_stringio.py

    do_bytesio.py

  • 相关阅读:
    mysql 主从架构搭建
    tomcat+nginx 反向代理 动静分离
    ELK(Elasticsearch + Logstash + Kibana)安装部署对nginx的日志收集
    Kibana server is not ready yet出现的原因
    apache+tomcat+单机双实例+动静分离+负载均衡
    docker的基本安装和简单使用+Dockerfile常用指令
    LVS+keepalived+DR 负载均衡高可用
    md5sum摘要
    python爬虫
    python和数据库
  • 原文地址:https://www.cnblogs.com/wanghuijie1/p/11884851.html
Copyright © 2011-2022 走看看