python - 从文件末尾寻找抛出不受支持的异常

标签 python python-3.x file

我有这个代码片段,我正在尝试使用 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 with seek(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/

相关文章:

python - 无法使正则表达式与 Python 一起使用

Python 自动选择串口(适用于 Arduino)

python - 使用 jupyter Notebook 在 conda 环境中设置 R

python - 如何格式化 AST 解析

ruby - 使用 Ruby SDK 从 Soundcloud 下载轨道

perl - 使用perl将基于染色体的 `.bed`文件拆分为 `chromosomeName.bed`

python - 千位分隔符未在 Django 管理中应用

Python3 : using matplotlib to create figure, 使用字典

python - 如何创建 Python stub 文件以及放置在哪里?

linux - 如何查找特定文件在给定时间范围内被修改的次数