如何创建和写入textiowrapper和readlines

时间:2017-06-22 14:36:02

标签: python encoding textwrapping readlines

所以我正在尝试创建一个文本io包装器,然后我可以使用readlines()来进行单元测试。这是我的尝试,但是当我运行它时,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

1 个答案:

答案 0 :(得分: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的有效值   文件可能取决于它是以文本还是二进制模式打开。

尝试以下评论代码段:

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

==>

<击>