在Python 3中逐行读取文件时捕获异常

pir*_*iri 6 python io exception python-3.x

请考虑以下代码:

with open('file.txt', 'r') as f:
    for line in f:
        print(line)
Run Code Online (Sandbox Code Playgroud)

在Python 3中,解释器尝试解码它读取的字符串,这可能会导致异常UnicodeDecodeError.这些当然可以try ... except在整个循环中用块来捕获,但我想在每个行的基础上处理它们.

问题:有没有办法直接捕获和处理读取的每一行的异常?希望没有改变过多迭代文件的简单语法?

Ser*_*sta 6

Pythonic方法可能是注册一个错误处理程序codecs.register_error_handler('special', handler)并在open函数中声明它:

with open('file.txt', 'r', error='special') as f:
    ...
Run Code Online (Sandbox Code Playgroud)

这样一来,如果有一个违规的行,那个handler将被调用的意志UnicodeDecodeError,并且能够返回一个替换字符串或重新引发错误.

如果您想要更明显的处理,另一种方法是以二进制模式打开文件并明确解码每一行:

with open('file.txt', 'rb') as f:
    for bline in f:
        try:
            line = bline.decode()
            print(line)
        except UnicodeDecodeError as e:
            # process error
Run Code Online (Sandbox Code Playgroud)


tim*_*geb 5

for您可以next自己调用文件迭代器并StopIteration手动捕获,而不是使用循环.

with open('file.txt', 'r') as f:
    while True:
        try:
            line = next(f)
            # code
        except StopIteration:
            break
        except UnicodeDecodeError:
            # code
Run Code Online (Sandbox Code Playgroud)