2017-06-22 35 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