FileNotFoundError in Python: Causes and Fixes with Simple Examples

 

What is FileNotFoundError in Python?

A FileNotFoundError in Python occurs when you try to open or access a file that does not exist at the specified location.

In simple words, Python is saying:

“I cannot find the file you are trying to open.”

This error is very common for beginners and usually appears when working with files, file paths, reading or writing files, and operating systems.


Understanding File Paths in Python

When working with files, Python needs the exact file name and correct path.

There are two types of file paths:

  • Relative path – File in the current folder

  • Absolute path – Full path of the file

If Python cannot locate the file using the given path, it raises a FileNotFoundError.


Common FileNotFoundError Message

A typical FileNotFoundError message looks like this:


FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'

This message tells us:

  • Python tried to access a file

  • The file does not exist in the given location


Example 1: FileNotFoundError While Reading a File

❌ Incorrect Code


file = open("data.txt", "r")
print(file.read())

❌ Error


FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'

✔ Why this happens

  • data.txt does not exist

  • Or the file is in a different folder

✔ Correct Code


file = open("data.txt", "w")
file.write("Hello Python")
file.close()

Then read it:


file = open("data.txt", "r")
print(file.read())

Example 2: FileNotFoundError Due to Wrong File Path

❌ Incorrect Code


file = open("files/data.txt", "r")

❌ Error


FileNotFoundError: [Errno 2] No such file or directory

✔ Correct Code (Absolute Path)


file = open("C:/Users/User/Documents/data.txt", "r")
print(file.read())

✔ Ensure the path is correct.


Example 3: FileNotFoundError with User Input

❌ Incorrect Code


filename = input("Enter file name: ")
file = open(filename, "r")

If the user enters a wrong file name:

❌ Error


FileNotFoundError: [Errno 2] No such file or directory

✔ Correct Code (Using try–except)


try:
    filename = input("Enter file name: ")
    file = open(filename, "r")
    print(file.read())
except FileNotFoundError:
    print("File not found. Please check the file name.")

Example 4: FileNotFoundError When Using open() Mode

❌ Incorrect Code


file = open("info.txt", "r")

❌ Error


FileNotFoundError

✔ Correct Code


file = open("info.txt", "a")
file.write("Python File Handling")
file.close()

✔ Mode "a" creates the file if it does not exist.


How to Debug FileNotFoundError Easily

Use these simple techniques:

✔ Check file name spelling
✔ Verify file location
✔ Print current working directory
✔ Use absolute paths
✔ Handle errors using try–except

Example:


import os
print(os.getcwd())

How to Avoid FileNotFoundError in Python

  • Always verify file paths

  • Use os.path.exists()

  • Use try–except blocks

  • Avoid hard-coded paths

  • Keep files organized

Example:


import os

if os.path.exists("data.txt"):
    print("File exists")
else:
    print("File not found")

Summary

FileNotFoundError in Python occurs when Python cannot locate the specified file.

Once you understand file paths and use proper error handling, this error becomes easy to fix.

This is a very common error while learning Python - keep practicing 


Frequently Asked Questions (FAQ)

Q1: Is FileNotFoundError a syntax error?
No, it occurs at runtime.

Q2: Can FileNotFoundError stop my program?
Yes, unless handled properly.

Q3: Is FileNotFoundError common for beginners?
Yes, extremely common.


📌 Final Tip

Always check whether a file exists before opening it in Python.


Comments

Popular posts from this blog

AttributeError in Python: Causes and Fixes with Simple Examples

SyntaxError in Python: Causes and Fixes with Simple Examples

SystemExit in Python: Causes and Fixes with Simple Examples