如何创建和写入textiowrapper和readlines

问题描述 投票:0回答:1

因此,我正在尝试创建一个文本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
python encoding word-wrap readlines
1个回答
5
投票

TextIOWrapper

模块文档中阅读大约
io
类:

二进制流上的缓冲文本流。

Edit
:使用BufferedIOBase功能:

seek 将流位置更改为给定的字节偏移。

seek(offset[, whence])
是 相对于

offset
表示的位置进行解释。默认值
whence
的值是

whence

SEEK_SET
值为:
whence
或0 - 流的启动(默认值);偏移应为零或正

SEEK_SET
    或1 - 当前流动位置;偏移可能为负
  • SEEK_CUR
    或2 - 流的末端;偏移通常为负
  • 回收新的绝对位置。
    3.1版中的新闻:
    SEEK_END
  • 常量。 3.3版中的新闻:某些操作系统可以支持其他 值,例如
  • 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)

    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.