python - 如何创建和写入 textiowrapper 和 readlines

标签 python encoding word-wrap readlines

所以我尝试创建一个文本 io 包装器,然后我可以使用 readlines() 进行单元测试。这是我的尝试,但是当我运行它时 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

最佳答案

了解 TextIOWrapper classio模块文档:

A buffered text stream over a BufferedIOBase binary stream.

编辑:使用seek功能:

seek(offset[, whence])

Change the stream position to the given byte offset. offset is interpreted relative to the position indicated by whence. The default value for whence is SEEK_SET. Values for whence are:

  • SEEK_SET or 0 – start of the stream (the default); offset should be zero or positive
  • SEEK_CUR or 1 – current stream position; offset may be negative
  • SEEK_END or 2 – end of the stream; offset is usually negative

Return the new absolute position.

New in version 3.1: The SEEK_* constants.

New in version 3.3: Some operating systems could support additional values, like os.SEEK_HOLE or os.SEEK_DATA. The valid values for a file could depend on it being open in text or binary mode.

尝试以下注释代码片段:

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

==>

<罢工>

关于python - 如何创建和写入 textiowrapper 和 readlines,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44702487/

相关文章:

python - Numpy 掩码数组修改

python - 'charmap' 编解码器无法解码位置 33222 : character maps to <undefined> 中的字节 0x8d

来自 Powershell 和 Windows 编码的 MysqlDump

vim - 如何防止 Vim 缩进括号中的换行文本

python - 解析 XML 以存储在数据库中

python - 计算从 4 个 mysql 表中检索到的所有可能文本对的余弦相似度

c# - 在 dotnet core 中使用密码和盐对字符串进行编码和解码

c# - Wpf RichTextBox 换行问题

html - 在伪元素周围包装 header 和 p

python - 为什么我创建的 postgres 用户被拒绝访问表?