Exceptions

Author

Clayton Cafiero

Published

2025-06-23

Exceptions

FileNotFoundError

This is just as advertised: an exception which is raised when a file is not found. This is almost always due to a typo or misspelling in the filename, or that the correct path is not included.

Suppose there is no file in our file system with the name some_non-existent_file.foobar. Then, if we were to try to open a file without creating it, we’d get a FileNotFoundError.

>>> with open("some_non-existent_file.foobar") as fh:
...     s = fh.read()
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 
        'some_non-existent_file.foobar'

Usually we can fix this by supplying the correct filename or a complete path to the file.

UnicodeDecodeError

A UnicodeDecodeError occurs if we try to decode a string that was encoded in a different system. This can occur when reading data from a file or other source. Example (assuming data.txt was encoded with, say, Windows-1252 encoding):

with open("data.txt") as fh:
    s = fh.read()

will result in a UnicodeDecodeError if there are any invalid UTF-8 encodings in the input. To fix, specify the correct encoding:

with open("data.txt", encoding=cp1252) as fh:
    s = fh.read()

For a more detailed explanation of Unicode, UnicodeDecodeError, and UnicodeEncodeError, see Appendix I: The joy of Unicode (but don’t say I didn’t warn you—the details may make your head spin).

Copyright © 2023–2025 Clayton Cafiero

No generative AI was used in producing this material. This was written the old-fashioned way.