的io
模塊文檔閱讀TextIOWrapper
class :
具有緩衝的文本流過BufferedIOBase
binary stream。
編輯:使用seek
功能:
seek(offset[, whence])
更改流位置給定的字節偏移。 offset
是 相對於由whence
指示的位置解釋。 whence
的默認 值爲SEEK_SET
。 whence
的值爲:
SEEK_SET
或0 - 流的開始(缺省值);偏移應爲零或正數
SEEK_CUR
或1-當前數據流位置;偏移可能爲負數
SEEK_END
或2 - 流結束;偏移量通常爲負值
返回新的絕對位置。
版本3.1的新功能:SEEK_*
常量。
版本3.3中的新功能:某些操作系統可能支持其他 值,如os.SEEK_HOLE
或os.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
==>
是新的答案工作。看起來我錯過了'wrapper.seek(0,0)'調用來啓動流。 – EliSquared