从文件末尾查找引发不支持的异常 [英] Seeking from end of file throwing unsupported exception

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

问题描述

我有此代码段,我正在尝试使用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)

这会在运行时引发以下异常:

This throws the following exception while running:

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的文件),仅允许相对于文件开头的查找(查找到以seek(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)).

因此,您可以将程序更改为:

Therefore, you can change your program to read:

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

但是,您应该意识到,在阅读或编写文本时添加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. For a more thorough discussion of the cause of the problem, and a solution that does not require adding the b flag, see another answer to this question.

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

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