zoukankan      html  css  js  c++  java
  • 内存数据的读取

    python : StringIO 和 BytesIO:

    --数据读写不一定是文件,也可以在内存中读写

    StringIO:

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

    
    from io import StringIO
    f= StringIO()
    f.write('')  # 写入
    
    ---》f.getvalue()   #获取写入的数据(str)
    
    
    --StringIO操作的只能是str!!
    --读取StringIO,用一个str初始化StringIO,像读文件一样读取
    

    BytesIO:

    要操作二进制数据,就需要使用BytesIO

    BytesIO实现了在内存中读写bytes
    
    >>> from io import BytesIO
    
    >>> f = BytesIO()
    
    >>> f.write('中文'.encode('utf-8'))
    
    6
    
    >>> print(f.getvalue())
    
    b'xe4xb8xadxe6x96x87'
    
    #读取数据
    
    >>> from io import BytesIO
    
    >>> f = BytesIO(b'xe4xb8xadxe6x96x87')
    
    >>> f.read()  # 只能读一次,再读为空。 可以把f.read()赋给某个变量,然后解码变量,显示值
    
    
    #样式一:
    >>> from io import StringIO   #  导入StringIO类
    
    >>> f = StringIO()     # 创建一个实例,赋给f对象
    
    >>> f.write('hello')    #  往 f 中写入
    
    5
    
    >>> f.write(' ')
    
    1
    
    >>> f.write('world!')
    
    6
    
    >>> print(f.getvalue())  #getvalue()方法用于获得写入后的str
    
    hello world!
    
    #样式二:
    >>> from io import StringIO
    
    >>> f = StringIO('Hello!
    Hi!
    Goodbye!')     #创建一个带内容的实例
    
    >>> while True:      # while循环
    
    ...     s = f.readline()  # 按行读取内容
    
    ...     if s == '':
    
    ...         break
    
    ...     print(s.strip())   # strip(),删除行首行尾的空格
    

    总结:

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

  • 相关阅读:
    [HNOI 2010]Bus 公交线路
    [HNOI 2010]Planar
    [HNOI 2010]chorus 合唱队
    定时器 @Scheduled定点启动
    mysql后获取时间
    kafka基本原理
    cron定时表达式
    自定义导出
    java指定年月的天数和周数<br>
    Date和Calendar时间操作常用方法及示例
  • 原文地址:https://www.cnblogs.com/shaozheng/p/12011225.html
Copyright © 2011-2022 走看看