Exceptions

Published

2023-07-31

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.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

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

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).