![]() |
VOOZH | about |
FileNotFoundError is a built-in Python exception that is raised when an operation such as reading, writing or deleting is attempted on a file that does not exist at the specified path. It is a subclass of OSError and commonly occurs when functions like open(), os.remove() and similar file-handling methods are used without first checking if the file is actually present. Example:
Output
Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 1, in <module>
file = open("abc.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'
Let’s look at a few simple ways to fix FileNotFoundError and make sure your program keeps running smoothly even if a file is missing.
Python provides the os.path.exists() method from the built-in os module to check whether a file exists at a given path.
Not found!
Try block is a reliable way to handle FileNotFoundError. It lets your program attempt to open the file, and if the file doesn’t exist, the except block gracefully handles the error without crashing the program.
Not found
Absolute path specify the exact location of the file on your system, removing any ambiguity about where Python should look for it.
If the file does not exist, using write mode ("w") in Python will automatically create it. This is useful when you want to ensure the file exists, even if it wasn't there before.
Output