Handle FileNotFoundError in Python

In Python, the FileNotFoundError occurs when attempting to open a file that does not exist. To handle this error, we use a try-except block to catch the exception and provide an alternative action, such as displaying a custom message or creating the missing file. Below, we explore multiple ways to handle FileNotFoundError effectively.


Examples

1. Handling FileNotFoundError with a Try-Except Block

The simplest way to handle FileNotFoundError is by using a try-except block to catch the error and display an appropriate message.

main.py

</>
Copy
try:
    # Attempt to open a non-existent file
    file = open("non_existent_file.txt", "r")
    content = file.read()
    file.close()
except FileNotFoundError:
    print("Error: The file does not exist. Please check the file name or path.")

Explanation:

Here, we use a try-except block:

  • open("non_existent_file.txt", "r"): Attempts to open a file that does not exist.
  • If the file is not found, Python raises a FileNotFoundError, which is caught by the except block.
  • The print() statement inside the except block informs the user that the file is missing.

Output:

2. Creating the File If It Does Not Exist

If the file does not exist, we can create it automatically to prevent the error.

main.py

</>
Copy
try:
    file = open("new_file.txt", "r")
    content = file.read()
    file.close()
except FileNotFoundError:
    print("File not found! Creating a new file...")
    with open("new_file.txt", "w") as file:
        file.write("This is a newly created file.")

Explanation:

In this approach:

  • We try to open new_file.txt.
  • If it does not exist, the except block executes, printing a message and creating a new file.
  • The open("new_file.txt", "w") line creates a new file in write mode.
  • We write the text "This is a newly created file." to the file.

Output:

Let us check the file.

3. Using os.path.exists() to Check File Existence

We can use the os.path.exists() function to check if a file exists before attempting to open it.

main.py

</>
Copy
import os

file_path = "sample.txt"

if os.path.exists(file_path):
    with open(file_path, "r") as file:
        content = file.read()
        print("File content:", content)
else:
    print("Error: The file does not exist.")

Explanation:

Here:

  • The os.path.exists(file_path) function checks if sample.txt exists.
  • If the file exists, it is opened and read; otherwise, an error message is displayed.

Output (if file exists):

Output (if file does not exist):

Error: The file does not exist.

4. Providing a Default File Path

If a file is missing, we can provide a default file path to avoid errors.

main.py

</>
Copy
default_file = "default.txt"

try:
    file = open("missing_file.txt", "r")
except FileNotFoundError:
    print(f"File not found! Using default file: {default_file}")
    file = open(default_file, "r")

content = file.read()
file.close()
print("File Content:", content)

Explanation:

In this method:

  1. We try to open missing_file.txt.
  2. If the file is missing, we use default.txt instead.

Output (if file is missing):

Conclusion

In this tutorial, we have covered use cases on how to handle FileNotFoundError with the following scenarios:

  • Use try-except to catch and handle errors.
  • Create a new file if it does not exist.
  • Check file existence with os.path.exists().
  • Provide a default file path.