我有这个代码片段,我正在尝试使用 python 从文件末尾向后搜索:
f=open('D:\SGStat.txt','a');
f.seek(0,2)
f.seek(-3,2)
这会在运行时引发以下异常:
f.seek(-3,2)
io.UnsupportedOperation: can't do nonzero end-relative seeks
我在这里错过了什么吗?
最佳答案
来自 documentation对于 Python 3.2 及更高版本:
In text files (those opened without a
b
in the mode string), only seeks relative to the beginning of the file are allowed (the exception being seeking to the very file end withseek(0, 2)
).
这是因为文本文件在编码字节和它们所代表的字符之间没有一一对应的关系,所以 seek
无法告诉在文件中跳转到哪里移动一定数量的字符。
如果您的程序可以处理原始字节,您可以将程序更改为读取:
f = open('D:\SGStat.txt', 'ab')
f.seek(-3, 2)
注意模式字符串中的b
,用于二进制文件。 (还要注意删除了多余的 f.seek(0, 2)
调用。)
但是,您应该知道,在读取或写入文本时添加 b
标志可能会产生意想不到的后果(例如使用多字节编码),实际上是 changes the type of data read or written .
关于python - 从文件末尾寻找抛出不受支持的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21533391/