从文件末尾寻找抛出不受支持的异常 [英] Seeking from end of file throwing unsupported exception

查看:24
本文介绍了从文件末尾寻找抛出不受支持的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码片段,我正在尝试使用 python 从文件末尾向后查找:

I have this code snippet and I'm trying to seek backwards from the end of file using 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

我在这里遗漏了什么吗?

Am i missing something here?

推荐答案

来自 文档 适用于 Python 3.2 及更高版本:

From the documentation for Python 3.2 and up:

在文本文件中(在模式字符串中没有 b 的情况下打开的文件),只允许相对于文件开头的搜索(例外是搜索到带有 的文件结尾)寻求(0, 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 无法知道要跳转到文件中的哪个位置来移动一定数量的字符.

This is because text files do not have a 1-to-1 correspondence between encoded bytes and the characters they represent, so seek can't tell where to jump to in the file to move by a certain number of characters.

如果您的程序可以处理原始字节,您可以将程序更改为读取:

If your program is okay with working in terms of raw bytes, you can change your program to read:

f = open('D:SGStat.txt', 'ab')
f.seek(-3, 2)

注意模式字符串中的 b,对于二进制文件.(还要注意删除了多余的 f.seek(0, 2) 调用.)

Note the b in the mode string, for a binary file. (Also note the removal of the redundant f.seek(0, 2) call.)

但是,您应该意识到在读取或写入文本时添加 b 标志可能会产生意想不到的后果(例如多字节编码),事实上 更改读取或写入的数据类型.

However, you should be aware that adding the b flag when you are reading or writing text can have unintended consequences (with multibyte encoding for example), and in fact changes the type of data read or written.

这篇关于从文件末尾寻找抛出不受支持的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆