Exception exception while reading a file line by line in Python 3

Consider the following code:

with open('file.txt', 'r') as f:
    for line in f:
        print(line)

In Python 3, the interpreter tries to decode the lines it reads, which can lead to type exceptions UnicodeDecodeError. Of course, they can be captured by the block try ... exceptaround the entire cycle, but I would like to process them separately.

Question: Is there a way to directly catch and handle exceptions for each line read? Hopefully without changing the simple syntax of iterating over a file too much?

+4
source share
3 answers

Pythonic's path is likely to register an error handler with codecs.register_error_handler('special', handler)and declare it in an open function:

with open('file.txt', 'r', error='special') as f:
    ...

, , 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
+4

for next - StopIteration.

with open('file.txt', 'r') as f:
    while True:
        try:
            line = next(f)
            # code
        except StopIteration:
            break
        except UnicodeDecodeError:
            # code
+4

Put your try-except catch in a for loop, for example:

with open('file.txt', 'r') as f:
    for line in f:
      try:  
        print(line)
      except:
        print("uh oh")
        # continue
-1
source

Source: https://habr.com/ru/post/1689730/


All Articles