zoukankan      html  css  js  c++  java
  • python3(三十六)StringIO BytesIO

    """ StringIO和BytesIO """
    __author__on__ = 'shaozhiqi  2019/9/23'
    
    # !/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    # 很多时候,数据读写不一定是文件,也可以在内存中读写。
    # 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。
    
    from io import StringIO
    
    f = StringIO('Hello!
    Hi!
    Goodbye!')
    while True:
        s = f.readline()
        if s == '':
            break
        print(s.strip())
        # Hello!
        # Hi!
        # Goodbye!
    
        # ----------------------------------------------------------------------------
        # StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO。
        # BytesIO实现了在内存中读写bytes,我们创建一个BytesIO,然后写入一些bytes:
    
    from io import BytesIO
    
    f = BytesIO()
    f.write('中文'.encode('utf-8'))
    print(f.getvalue())
    # b'xe4xb8xadxe6x96x87'
    # 请注意,写入的不是str,而是经过UTF-8编码的bytes。
    # 和StringIO类似,可以用一个bytes初始化BytesIO,然后,像读文件一样读取:
    
    from io import BytesIO
    
    f = BytesIO(b'xe4xb8xadxe6x96x87')
    print(f.read())
    # b'xe4xb8xadxe6x96x87'
  • 相关阅读:
    Java并发与线程同步
    ArrayList源码分析
    Lock之ReentrantLock及实现生产者消费者和死锁
    SimpleDateFormat线程不安全原因及解决方案
    JDK1.7 hashMap源码分析
    java 数据操作
    java 数据流操作
    java 基础概念
    获取class 信息 java
    Java虚拟机系列(三)---内存溢出情况及解决方法
  • 原文地址:https://www.cnblogs.com/shaozhiqi/p/11574074.html
Copyright © 2011-2022 走看看