下载安卓APP箭头
箭头给我发消息

客服QQ:3315713922

python应用:io文本、十进制和原始流I/O工具

作者:@小灰灰     来源: https://www.cnblogs.com/liuhui0308/p/12497546.html点击数:819发布时间: 2020-04-01 10:08:18

标签: python编程语言Python语言

大神带你学编程,欢迎选课

由于Python语言的简洁性、易读性以及可扩展性,在国外用Python做科学计算的研究机构日益增多,一些知名大学已经采用Python来教授程序设计课程。例如卡耐基梅隆大学的编程基础、麻省理工学院的计算机科学及编程导论就使用Python语言讲授。

io模块在解释器的内置open()之上实现了一些类来完成基于文件的输入和输出操作。这些类得到了适当的分解,从而可以针对不同的用途重新组合——例如,支持向一个网络套接字写Unicode数据。

1.1 内存中的流

StringIO提供了一种很便利的方式,可以使用文件API(如read()、write()等)处理内存中的文本。有些情况下,与其他一些字符串连接技术相比,使用StringIO构造大字符串可以提供更好的性能。内存中的流缓冲区对测试也很有用,写入磁盘上真正的文件并不会减慢测试套件的速度。

下面是使用StringIO缓冲区的一些标准例子。

  1. import io
  2. # Writing to a buffer
  3. output = io.StringIO()
  4. output.write('This goes into the buffer. ')
  5. print('And so does this.', file=output)
  6. # Retrieve the value written
  7. print(output.getvalue())
  8. output.close()# discard buffer memory
  9.  
  10. # Initialize a read buffer
  11. input = io.StringIO('Inital value for read buffer')
  12. # Read from the buffer
  13. print(input.read())

这个例子使用了read(),不过也可以用readline()和readlines()方法。StringIO类还提供了一个seek()方法,读取文本时可以在缓冲区中跳转,如果使用一种前向解析算法,则这个方法对于回转很有用。

 

要处理原始字节而不是Unicode文本,可以使用BytesIO。

  1. import io
  2. # Writing to a buffer
  3. output = io.BytesIO()
  4. output.write('This goes into the buffer. '.encode('utf-8'))
  5. output.write('ÁÇÊ'.encode('utf-8'))
  6. # Retrieve the value written
  7. print(output.getvalue())
  8. output.close()# discard buffer memory
  9.  
  10. # Initialize a read buffer
  11. input = io.BytesIO(b'Inital value for read buffer')
  12. # Read from the buffer
  13. print(input.read())

写入BytesIO实例的值一定是bytes而不是str。

 

 

1.2 为文本数据包装字节流

原始字节流(如套接字)可以被包装为一个层来处理串编码和解码,从而可以更容易地用于处理文本数据。TextIOWrapper类支持读写。write_through参数会禁用缓冲,并且立即将写至包装器的所有数据刷新输出到底层缓冲区。 

  1. import io
  2. # Writing to a buffer
  3. output = io.BytesIO()
  4. wrapper = io.TextIOWrapper(
  5. output,
  6. encoding='utf-8',
  7. write_through=True,
  8. )
  9. wrapper.write('This goes into the buffer. ')
  10. wrapper.write('ÁÇÊ')
  11. # Retrieve the value written
  12. print(output.getvalue())
  13. output.close()# discard buffer memory
  14.  
  15. # Initialize a read buffer
  16. input = io.BytesIO(
  17. b'Inital value for read buffer with unicode characters '+
  18. 'ÁÇÊ'.encode('utf-8')
  19. )
  20. wrapper = io.TextIOWrapper(input, encoding='utf-8')
  21. # Read from the buffer
  22. print(wrapper.read())

这个例子使用了一个BytesIO实例作为流。对应bz2、http,server和subprocess的例子展示了如何对其他类型的类似文件的对象使用TextIOWrapper。

Python在设计上坚持了清晰划一的风格,这使得Python成为一门易读、易维护,并且被大量用户所欢迎的、用途广泛的语言。

赞(10)
踩(0)
分享到:
华为认证网络工程师 HCIE直播课视频教程