A FileNotFoundError occurs when Python tries to access a file that does not exist at the specified location. This exception is a subclass of OSError and is commonly raised while opening, reading, deleting, or modifying files.
file = open("abc.txt")
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'
Explanation: Python looks for the file abc.txt in the current working directory. Since the file does not exist, it raises a FileNotFoundError.
Common Causes
1. File Does Not Exist: This is the most common reason for the error.
with open("report.txt", "r") as file:
print(file.read())
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'report.txt'
Explanation: Python cannot find the file report.txt because it does not exist in the specified location.
2. Incorrect File Path: A typo in the file path or filename can also trigger this exception.
with open("documents/data.txt", "r") as file:
print(file.read())
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'documents/data.txt'
Explanation: directory or file path is incorrect, so Python is unable to locate the file.
3. Wrong Current Working Directory: Sometimes the file exists, but Python is searching in a different directory.
import os
print(os.getcwd())
with open("data.txt", "r") as file:
print(file.read())
Output
C:\Users\User\Projects
ERROR!
Traceback (most recent call last):
...
FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'
Explanation: file may exist elsewhere, but Python only searches relative paths from the current working directory.
Handling FileNotFoundError
1. Check if the File Exists Before Opening: You can use os.path.exists() to verify the file's presence before accessing it.
import os
fp = "abc.txt"
if os.path.exists(fp):
with open(fp, "r") as file:
print(file.read())
else:
print("File not found.")
Output
File not found.
Explanation: program first checks whether the file exists. If it does not exist, a message is displayed instead of raising an exception.
2. try-except Block: A try-except block allows you to handle the exception gracefully.
try:
with open("abc.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("File not found.")
Output
File not found.
Explanation: If the file is missing, Python raises a FileNotFoundError, which is caught by the except block and handled safely.
3. Absolute File Path: An absolute path specifies the exact location of the file.
with open("C:/Users/User/Documents/abc.txt", "r") as file:
print(file.read())
Output
File contents displayed here
Explanation: Using the complete file path removes ambiguity and helps Python locate the file correctly.
4. Create the File if It Does Not Exist: If your goal is to create a file when it is missing, use write mode ("w").
with open("abc.txt", "w") as file:
file.write("This file has been created!")
Output
abc.txt file created successfully
Explanation: When a file is opened in write mode and does not exist, Python automatically creates it.