zoukankan      html  css  js  c++  java
  • pythonIO流的理解

    Python识别的文件可以存储三种类型的数据:文本、二进制、原始数据

    Python 将属于上述三类的对象视为“类文件对象”。它们也称为流,可以从中读取或写入数据。存储在流中的数据称为该流的缓冲区。前两个,即 Text 和 Binary 流,是缓冲的 I/O 流,原始类型是无缓冲的。

    使用python对磁盘文件进行操作

    with open('file.txt', 'mode') as f: 
    

    它执行以下操作

    1、以“mode”模式打开一个类似文件的对象“file.ext ”。它返回一个流 f

    2、f 是一个可以随机/顺序访问其缓冲区的流

    3、我们可以根据模式读取/写入该流

    在 Python 中,我们还可以创建可以容纳不同类型缓冲区的内存流。Python 的io包提供了两个类:

    StringIO:用于存储 UTF-8 字符串缓冲区
    BytesIO:用于存储二进制缓冲区

    文本流

    from io import StringIO
    
    text_stream = StringIO()
    text_stream.write("I am a text buffer")
    
    print(text_stream.getvalue()) # Prints 'I am a text buffer' to console
    text_stream.close()
    

    程序创建一个新的文本流,将一些数据写入其缓冲区,然后将缓冲区内容打印到控制台

    Python 的 print 语句采用一个称为关键字参数的关键字参数file,该参数决定将给定的消息/对象写入哪个流。它的值是一个“类文件对象”

    print( *objects , sep=' ' , end='
    ' , file=sys.stdout , flush=False )
    # sys.stdout默认控制台输出
    

    我们可以更改和自定义流

    from io import StringIO
    
    text_stream = StringIO()
    text_stream.write("I am a text buffer")
    
    print(" in python", file=text_stream) # Doesn't print to console, instead writes to stream
    print(text_stream.getvalue()) # Prints 'I am a text buffer in python' to console
    text_stream.close()
    

    二进制流
    二进制流存储和操作二进制数据(字节)。它具有与 StringIO 相同的方法,如getvalue, read, write。除了,它在内部对不同类型的缓冲区数据进行操作,我们用一些数据创建一个内存中的二进制流。然后,我们可以使用该getvalue方法读取缓冲区的内容。如果我们尝试将二进制流的内容复制到文本流中,它会抛出TypeError

    from io import BytesIO, StringIO
    
    binary_stream =  BytesIO(b'I am a byte string x01')
    
    print(binary_stream.getvalue()) # Prints b'I am a byte string x01'
    
    try:
      text_stream = StringIO(binary_stream.getvalue())
    except TypeError:
      print('Sorry, text stream cannot store bytes') # Prints 'Sorry, text stream cannot store bytes'
    

    可以将来自 PDF 或 ZIP 文件的任何二进制数据存储到自定义二进制流中

  • 相关阅读:
    揺する、揺らす、揺さぶる区別
    test
    W5N1のW2D2
    微软企业库6的使用方法
    Delphi XE6 原生解析json
    delphi URL 编码的转换
    Go语言配置与开发环境配置
    Win7 IIS下启用ASP.NET
    Windows2003远程桌面单会话登录
    IIS7应用程序池集成和经典的区别
  • 原文地址:https://www.cnblogs.com/P-Z-W/p/15129059.html
Copyright © 2011-2022 走看看