Exceptions
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.
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.