因此,我正在尝试创建一个文本io包装器,然后我可以使用readlines()来实现Untiment()。这是我的尝试,但是当我运行它时,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
模块文档中阅读大约
io
类:
Edit:使用BufferedIOBase
功能:
seek
将流位置更改为给定的字节偏移。
seek(offset[, whence])
是
相对于offset
表示的位置进行解释。默认值输出的值是
whence
whence
。SEEK_SET
值为:或0 - 流的启动(默认值);偏移应为零或正
whence
SEEK_SET
或1 - 当前流动位置;偏移可能为负
或2 - 流的末端;偏移通常为负SEEK_CUR
- 常量。 3.3版中的新闻:某些操作系统可以支持其他 值,例如
回收新的绝对位置。 3.1版中的新闻:SEEK_END
- 。一个有效值 文件可能取决于在文本或二进制模式下打开的文件。
SEEK_*
或os.SEEK_HOLE
步调以下
COMEMENTECED代码段:
os.SEEK_DATA
我原来的其余答案:
import io, os output = io.BytesIO() wrapper = io.TextIOWrapper( output, encoding='cp1252', # errors=None, # default # newline=None, # default line_buffering=True, # write_through=False # default ) 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 debugging purposes
print( wrapper.write('Text4\n')) # for debugging purposes
# for line in wrapper.read():
for line in output.getvalue().decode('cp1252').split(os.linesep):
print(line)