2017-06-22 160 views
0

所以我想创建一个文本io包装,然后我可以使用readlines()从单元测试。这里是我的尝试,但是当我运行它readlines方法()返回任何内容:如何创建和写入textirowrapper和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 
+0

是新的答案工作。看起来我错过了'wrapper.seek(0,0)'调用来启动流。 – EliSquared

回答

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

请尝试以下评论说代码片段:

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 

==> 

+0

问题是output.getvalue()的对象。decode('cp1252')'没有'readlines()'属性,如果我做'wrapper.readlines()'没有返回任何东西。有什么方法可以更改对象,以便您可以使用readlines()?我不想更改我的代码的功能以使单元测试正常工作。 – EliSquared