Introduction
In Python, a FileNotFoundError
occurs when an attempt is made to open a file that does not exist or is inaccessible. This exception can be handled using a try-except block, allowing the program to manage the error gracefully instead of crashing.
This tutorial will guide you through creating a Python program that demonstrates how to handle the FileNotFoundError
exception.
Example:
- Operation: Attempting to open a file named
example.txt
that does not exist. - Exception:
FileNotFoundError
- Program Output:
Error: The file 'example.txt' was not found.
Problem Statement
Create a Python program that:
- Attempts to open a file specified by the user.
- Catches and handles the
FileNotFoundError
if the file does not exist. - Prints an appropriate error message when the exception occurs.
Solution Steps
- Prompt for the File Name: Use the
input()
function to get the file name from the user. - Attempt to Open the File: Use a try-except block to attempt to open the file.
- Handle the Exception: Catch the
FileNotFoundError
and print an error message. - Read the File (If Found): If no exception occurs, read and display the file’s contents.
Python Program
# Python Program to Handle File Not Found Exception
# Author: https://www.rameshfadatare.com/
# Step 1: Prompt for the File Name
file_name = input("Enter the file name: ")
# Step 2: Attempt to Open the File
try:
with open(file_name, 'r') as file:
# Step 4: Read the File (If Found)
content = file.read()
print("File Content:")
print(content)
# Step 3: Handle the Exception
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
Explanation
Step 1: Prompt for the File Name
- The program prompts the user to input the name of the file they want to open using the
input()
function. The file name is stored in thefile_name
variable.
Step 2: Attempt to Open the File
- The program attempts to open the specified file in read mode (
'r'
) using awith
statement. Thewith
statement ensures that the file is properly closed after its block of code runs, even if an exception occurs.
Step 3: Handle the Exception
- If the file does not exist, a
FileNotFoundError
is raised. Theexcept FileNotFoundError
block catches this exception and prints an error message informing the user that the file was not found.
Step 4: Read the File (If Found)
- If the file is found and successfully opened, the program reads its contents using the
read()
method and prints the contents to the console.
Output Example
Example Output 1: File Not Found
Enter the file name: non_existent_file.txt
Error: The file 'non_existent_file.txt' was not found.
Example Output 2: File Found
Enter the file name: existing_file.txt
File Content:
Hello, this is a test file.
Additional Examples
Example 1: Handling Multiple Exceptions
try:
file_name = input("Enter the file name: ")
with open(file_name, 'r') as file:
content = file.read()
print("File Content:")
print(content)
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
except PermissionError:
print(f"Error: You do not have permission to read the file '{file_name}'.")
Output:
Enter the file name: restricted_file.txt
Error: You do not have permission to read the file 'restricted_file.txt'.
- This example handles both
FileNotFoundError
andPermissionError
, which occurs if the file exists but the user does not have permission to read it.
Example 2: Using finally Block
try:
file_name = input("Enter the file name: ")
with open(file_name, 'r') as file:
content = file.read()
print("File Content:")
print(content)
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
finally:
print("File operation completed.")
Output:
Enter the file name: non_existent_file.txt
Error: The file 'non_existent_file.txt' was not found.
File operation completed.
- The
finally
block is executed regardless of whether an exception occurred, which is useful for performing cleanup actions.
Example 3: Creating the File if Not Found
try:
file_name = input("Enter the file name: ")
with open(file_name, 'r') as file:
content = file.read()
print("File Content:")
print(content)
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
with open(file_name, 'w') as file:
file.write("This is a new file created by the program.")
print(f"The file '{file_name}' has been created.")
Output:
Enter the file name: new_file.txt
Error: The file 'new_file.txt' was not found.
The file 'new_file.txt' has been created.
- This example handles the
FileNotFoundError
by creating a new file if it does not exist.
Conclusion
This Python program demonstrates how to handle the FileNotFoundError
exception using a try-except block. By handling exceptions, you can make your programs more robust and user-friendly, preventing them from crashing when unexpected errors occur. Exception handling is an essential skill in Python programming that helps you manage errors gracefully and maintain control over your program’s execution flow.