Python 3 中的一个变化是在普通文本模式下删除了从文件末尾查找的能力。那么,通常接受的替代方案是什么呢?
例如,在 Python 2.7 中,我会输入 file.seek(-3,2)。
我已经了解了一些他们为什么这样做的原因,所以请不要只链接到 PEP。我知道使用 'rb' 可以允许我查找,但这会使我的文本文件以错误的格式读取。
Python 3 中的一个变化是在普通文本模式下删除了从文件末尾查找的能力。那么,通常接受的替代方案是什么呢?
例如,在 Python 2.7 中,我会输入 file.seek(-3,2)。
我已经了解了一些他们为什么这样做的原因,所以请不要只链接到 PEP。我知道使用 'rb' 可以允许我查找,但这会使我的文本文件以错误的格式读取。
TextIOBase.buffer
属性在底层缓冲区对象上寻找,但此时你需要重新附加一个新的TextIOBase
包装器,因为当前包装器将不再知道它所处的位置:import io
file.buffer.seek(-3, 2)
file = io.TextIOWrapper(
file.buffer, encoding=file.encoding, errors=file.errors,
newline=file.newlines)
io.TextIOWrapper()
对象 中。>>> import io
>>> with open('demo.txt', 'w') as out:
... out.write('Demonstration\nfor seeking from the end')
...
38
>>> with open('demo.txt') as inf:
... print(inf.readline())
... inf.buffer.seek(-3, 2)
... inf = io.TextIOWrapper(inf.buffer)
... print(inf.readline())
...
Demonstration
35
end
import io
def textio_seek(fobj, amount, whence=0):
fobj.buffer.seek(amount, whence)
return io.TextIOWrapper(
fobj.buffer, encoding=fobj.encoding, errors=fobj.errors,
newline=fobj.newlines)
并将其用作:
with open(somefile) as file:
# ...
file = textio_seek(file, -2, 3)
# ...
使用文件对象作为上下文管理器仍然有效,因为原始文件对象引用仍附加在原始文件缓冲区对象上,因此仍可用于关闭文件。