【问题标题】:How to create and write to a textiowrapper and readlines如何创建和写入 textiowrapper 和 readlines
【发布时间】:2017-06-22 14:36:02
【问题描述】:

所以我正在尝试创建一个文本 io 包装器,然后我可以使用 readlines() from 进行单元测试。这是我的尝试,但是当我运行它时, readlines() 什么也不返回:

output = io.BytesIO()
wrapper =  io.TextIOWrapper(
 output,
 encoding='cp1252',
 line_buffering=True,
 )

wrapper.write('Text1')
wrapper.write('Text2')
wrapper.write('Text3')
wrapper.write('Text4')

for line in wrapper.readlines():
    print(line)

我需要改变什么才能得到这个输出:

 Text1
 Text2
 Text3
 Text4

【问题讨论】:

  • 是的,新答案有效。看起来我错过了启动流的 wrapper.seek(0,0) 调用。

标签: python encoding word-wrap readlines


【解决方案1】:

io 模块文档中了解TextIOWrapper class

BufferedIOBase binary stream 上的缓冲文本流

编辑:使用seek函数:

seek(offset[, whence])

将流位置更改为给定的字节偏移量。 offset 是 相对于whence 指示的位置进行解释。默认 whence 的值为 SEEK_SETwhence 的值为:

  • SEEK_SET 或 0 – 流的开始(默认);偏移量应为零或正数
  • SEEK_CUR 或 1 - 当前流位置;偏移量可能为负数
  • SEEK_END 或 2 – 流结束;偏移量通常为负数

返回新的绝对位置。

3.1 版中的新功能:SEEK_* 常量。

3.3 版中的新功能:某些操作系统可以支持额外的 值,例如 os.SEEK_HOLEos.SEEK_DATA。 a 的有效值 文件可能取决于它以文本或二进制模式打开。

试试下面的注释代码sn-p:

import io, os
output  = io.BytesIO()
wrapper = io.TextIOWrapper(
 output,
 encoding='cp1252',
 # errors=None,         #  defalut
 # newline=None,        #  defalut
 line_buffering=True,
 # write_through=False  #  defalut
 )

wrapper.write('Text1\n')
wrapper.write('Text2\n')
wrapper.write('Text3\n')
# wrapper.flush()                #  If line_buffering is True, flush() is implied
                                 ## when a call to write contains a newline character.

wrapper.seek(0,0)                #  start of the stream
for line in wrapper.readlines():
    print(line)

我原来的答案的其余部分:

罢工>

print(output.getvalue())         # for gebugging purposes

print( wrapper.write('Text4\n')) #  for gebugging purposes

# for line in wrapper.read():
for line in output.getvalue().decode('cp1252').split(os.linesep):
    print(line)

输出

==> D:\test\Python\q44702487.py
b'Text1\r\nText2\r\nText3\r\n'
6
Text1
Text2
Text3
Text4

==>

【讨论】:

  • 问题是output.getvalue().decode('cp1252') 的对象没有readlines() 的属性,如果我这样做wrapper.readlines() 没有任何返回。有什么方法可以更改对象以便您可以使用 readlines()?我不想更改代码的功能以使单元测试正常工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-17
  • 1970-01-01
  • 2011-12-11
  • 2014-10-07
  • 1970-01-01
  • 2012-07-15
相关资源
最近更新 更多