的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