Last Updated :
28 Apr, 2025
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:
Python
file = open("abc.txt")
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'
Solutions
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.
1. Check if file exits before opening
Python provides the os.path.exists() method from the built-in os module to check whether a file exists at a given path.
Python
import os fp = "abc.txt" if os.path.exists(fp): with open(fp, "r") as f: data = f.read() else: print("Not found!")
2. Using try-except block
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.
Python
try: with open("abc.txt", "r") as file: data = file.read() except FileNotFoundError: print("Not found")
3. Use absolute file path
Absolute path specify the exact location of the file on your system, removing any ambiguity about where Python should look for it.
Python
import os print("Current directory:", os.getcwd()) fp = "/absolute/path/to/abc.txt" # file path with open(fp, "r") as file: data = file.read()
4. Create the file if missing
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.
Python
with open("abc.txt", "w") as file: file.write("This file has been created!")
Output
-
File I/O in Python
-
Causes of
FileNotFoundError
in Python
The FileNotFoundError
is a popular error that arises when Python has trouble finding the file you want to open.
This article will discuss the FileNotFoundError
in Python and its solution.
File I/O in Python
Python has built-in functions which are used to modify files. A file is an object stored in the storage device on the computer.
Python’s open()
function is used to open files. It has two parameters.
Parameter | Description |
---|---|
filename |
The file’s name that you want to open. |
mode |
The operation which you want to do on the file. |
There are several modes that allow different operations.
Mode | Usage |
---|---|
r |
Open and read a file that already exists. |
a |
Open and append data to a file that already exists. |
w |
Open an existing file to write data onto it. Creates a new file if no file of the same name exists. |
Causes of FileNotFoundError
in Python
When opening files, an error called FileNotFoundError
may arise if Python cannot find the specified file to be opened. The example code below will produce the error that follows it.
Example Code:
# Python 3.x
file = open("text.txt", "r")
Output:
#Python 3.x
Traceback (most recent call last):
File "c:/Users/LEO/Desktop/Python/main.py", line 2, in <module>
datafile = open('text.txt','r')
FileNotFoundError: [Errno 2] No such file or directory: 'text.txt'
Reason 1 — File Not Present in the Current Directory
Usually, the primary reason is that the file is not in the same folder from which the code is being run. By default, the open()
function looks for the file in the same folder as where the code file is.
Suppose the directory structure looks like this.
code.py
my_folder
---my_file.txt
The error will raise if the user opens the my_file.txt
using the following code.
Example Code:
# Python 3.x
file = open("my_file.txt", "r")
Output:
#Python 3.x
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-4-0fc1710b0ae9> in <module>()
----> 1 file = open('my_file.txt','r')
FileNotFoundError: [Errno 2] No such file or directory: 'my_file.txt'
Reason 2 — Incorrect File Name or Extension
The user specifies an incorrect file name or extension if the error is faced even when the file is in the correct directory.
Suppose the user has a file named my_file.txt
. If the filename or the extension is incorrect, the error will raise in both situations.
Example Code:
# Python 3.x
file = open("my_file2.txt", "r")
Output:
#Python 3.x
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-5-4dd25a062671> in <module>()
----> 1 file = open('my_file2.txt','r')
FileNotFoundError: [Errno 2] No such file or directory: 'my_file2.txt'
Here’s another example.
Example Code:
# Python 3.x
file = open("my_file.jpg", "r")
Output:
#Python 3.x
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-6-d1645df0ff1f> in <module>()
----> 1 file = open('my_file.jpg','r')
FileNotFoundError: [Errno 2] No such file or directory: 'my_file.jpg'
Now let’s discuss the solution to the FileNotFoundError
in Python.
Solution 1 — Specify the Complete File Path
The first thing to check is whether the target file is in the correct folder. If it is not in the same folder as the code file, then it should be moved to the same folder as the code file.
If this is not an option, then you should give the complete file’s path in the file name parameter of the open function. File paths work in the following way on Windows:
C:\Users\username\filename.filetype
The complete path to the file must be given in the open function. An example code with a dummy path is mentioned below.
Example Code:
# Python 3.x
file = open(r"C:\Folder1\Subfolder1\text.txt")
Solution 2 -Specify Correct File Name and Extension
You can re-check the file name and the extension you want to open. Then write its correct name in the open()
method.
Suppose you want to open my_file.txt
. The code would be like the following.
Example Code:
# Python 3.x
file = open("my_file.txt", "r")
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Курс по Python: https://stepik.org/course/100707
На предыдущем занятии я отмечал, что если указать неверный путь к файлу, то возникнет ошибка:
FileNotFoundError
и программа
досрочно прерывается. Это неприятный момент, тем более, что программист наперед
не может знать, в каких условиях будет работать программа и вполне возможна
ситуация, когда ранее доступный файл становится недоступным, например, из-за
случайного его удаления, или изменении имени и т.п. То есть, при работе с
файлами нужно уметь обрабатывать исключение FileNotFoundError, чтобы
программа продолжала работать, даже если файл не будет найден.
Для обработки
подобных ошибок (или, как говорят, исключений) существует специальная группа
операторов:
try / except / finally
о которых мы
подробно будем говорить в части объектно-ориентированного программирования на Python. Но, несмотря
на то, что это выходит за рамки базового курса, я решил показать, как
использовать эти операторы при работе с файлами. Иначе, ваши программы будут
заведомо содержать серьезную уязвимость при обращении к файлам.
Формально,
операторы try / except / finally имеют,
следующий синтаксис (определение):
try:
блок операторов
критического кода
except
[исключение]:
блок операторов
обработки исключения
finally:
блок операторов
всегда исполняемых
вне зависимости, от
возникновения исключения
И в нашем случае
их можно записать, так:
try: file = open("my_file.txt", encoding='utf-8') s = file.readlines() print(s) file.close() except FileNotFoundError: print("Невозможно открыть файл")
Смотрите, здесь
функция open() находится
внутри блока try, поэтому, если
возникнет исключение FileNotFoundError, то выполнение программы перейдет в блок
except и отобразится
строка «Невозможно открыть файл». Иначе, мы прочитаем все строки из файла,
отобразим их в консоли и закроем файл.
Однако, и в
такой реализации не все гладко. В момент считывания информации из файла (в
методе readlines()) также может
возникнуть исключение из-за невозможности считывания информации из файла.
Поэтому, совсем надежно можно было бы реализовать эту программу, следующим
образом:
try: file = open("my_file.txt", encoding='utf-8') try: s = file.readline() print(s) finally: file.close() except FileNotFoundError: print("Невозможно открыть файл") except: print("Ошибка при работе с файлом")
Мы здесь
прописываем еще один вложенный блок try, который будет учитывать все
возможные исключения и при их возникновении мы обязательно перейдем в блок finally для закрытия
файла. Это важная процедура – любой ранее открытый файл (функцией open()) следует
закрывать, даже при возникновении исключений. И вот такая конструкция try / finally нам гарантирует
его закрытие, что бы ни произошло в момент работы с ним. Но блок try / finally не отлавливает
исключения, поэтому они передаются внешнему блоку try и здесь мы
должны их обработать. Я сделал это через второй блок except, в котором не
указал никакого типа исключений. В результате, он будет реагировать на любые не
обработанные ошибки, то есть, в нашем случае – на любые ошибки, кроме FileNotFoundError.
Менеджер контекста для файлов
Более я не буду
углубляться в работу блоков try / except / finally. Приведенного
материала пока вполне достаточно, а в заключение этого занятия расскажу о
замене блока try / finally так называемым
файловым менеджером контекста, как это принято делать в программах на Python.
Так вот, в языке
Python существует
специальный оператор with, который, можно воспринимать как аналог
конструкции try / finally и в случае
работы с файлами записывается, следующим образом:
try: with open("my_file.txt", encoding='utf-8') as file: s = file.readlines() print( s ) except FileNotFoundError: print("Невозможно открыть файл") except: print("Ошибка при работе с файлом")
Смотрите, мы
здесь сразу вызываем функцию open(), создается объект file, через который,
затем, вызываем методы для работы с файлом. Причем, все операторы должны быть
записаны внутри менеджера контекста, так как после его завершения файл
закрывается автоматически. Именно поэтому здесь нет необходимости делать это
вручную.
При работе с
менеджером контекста следует иметь в виду, что он не обрабатывает никаких
ошибок (исключений) и все, что происходит, передается вышестоящему блоку try, где они и
обрабатываются. Но в любом случае: произошли ошибки или нет, файл будет
автоматически закрыт. В этом легко убедиться, если добавить блок finally для оператора try, в котором
отобразить флаг закрытия файла:
try: with open("my_file.txt", encoding='utf-8') as file: s = file.readlines() print( s ) except FileNotFoundError: print("Невозможно открыть файл") except: print("Ошибка при работе с файлом") finally: print(file.closed)
После запуска
программы видим значение True, то есть, файл был закрыт. Даже если
произойдет критическая ошибка, например, вызовем функцию int() для строки s:
то, снова видим
значение True – файл был
закрыт. Вот в этом удобство использования менеджера контекста при работе с
файлами.
На этом мы
завершим наше ознакомительное занятие по обработке файловых ошибок. Пока будет
достаточно запомнить использование операторов try / except / finally при работе с
файлами, а также знать, как открывать файлы через менеджер контекста. На
следующем уроке мы продолжим тему файлов и будем говорить о способах записи
данных.
Курс по Python: https://stepik.org/course/100707
Видео по теме
In Python, there are two types of errors: syntax errors and exceptions. Syntax errors, also known as parsing errors, occur when Python’s parser encounters a syntax error. Exceptions, on the other hand, occur when syntactically correct Python code results in an error. The «File Not Found Error» in Python is an example of an exception.
The «File Not Found Error» (FileNotFoundError) is raised when Python code attempts to open a file that doesn’t exist, cannot be found at the specified location, or is not a regular file but a different kind of file system object. This can happen for several reasons:
- The file doesn’t exist
- The file is in a different directory than specified
- The program has insufficient permissions to access the file
- The ‘file’ is a symbolic link that points to a non-existent file
- The ‘file’ is actually a directory, named pipe, or other non-regular file type
When a «File Not Found Error» occurs, it interrupts the execution of the program. However, it can be handled through Python’s error handling mechanism (using «try» and «except» statements), preventing the program from crashing and providing an opportunity to handle the situation gracefully. This includes handling situations where the file you’re trying to open is not a regular file but a symbolic link, directory, or another type of file system object.
Different reasons for getting ‘File Not Found Error’
1. Incorrect File Path:
One of the most common causes of the ‘File Not Found Error’ is providing an incorrect file path. This could be due to a simple typo in the file name or directory, or using the wrong case in case-sensitive file systems.
# Incorrect file name
with open('wrong_name.txt', 'r') as f:
content = f.read()
2. File Does Not Exist:
Another straightforward cause is trying to access a file that does not exist in the file system. This could occur due to deleting a file manually while the Python program is still running or an error in the program that causes a file to be deleted prematurely.
# Nonexistent file
with open('nonexistent_file.txt', 'r') as f:
content = f.read()
3. Improper Use of Relative and Absolute Paths:
Errors often arise from confusion between relative and absolute file paths. Relative file paths are interpreted in relation to the current working directory, which might not be the same as the directory where the Python script is located. On the other hand, an absolute path is a full path to the location of a file, starting from the root directory.
# Incorrect relative path
with open('wrong_directory/my_file.txt', 'r') as f:
content = f.read()
# Incorrect absolute path
with open('/wrong_directory/my_file.txt', 'r') as f:
content = f.read()
4. Trying to Open a Non-regular File:
As mentioned previously, trying to open a file that is not a regular file can also cause a ‘File Not Found Error’. This includes symbolic links pointing to non-existent files, directories, named pipes, and more.
# Trying to open a symbolic link pointing to a nonexistent file
with open('symbolic_link_to_nonexistent_file', 'r') as f:
content = f.read()
5. Insufficient File Permissions:
If your program doesn’t have the necessary permissions to access a file, it can also result in a ‘File Not Found Error’. This is common in multi-user systems where file access permissions are strictly managed.
# File without necessary permissions
with open('restricted_file.txt', 'r') as f:
content = f.read()
How to Handle ‘File Not Found Error’
In Python, error handling is performed using the try-except statement. Here’s a basic structure:
try:
# code block where an exception might occur
except ExceptionType:
# code to be executed in case the exception occurs
You put the code that might throw an exception in the try block and the code to handle the exception in the except block. Python allows multiple except blocks to handle different types of exceptions separately. If an exception occurs in the try block, Python will stop executing further code in the try block and jump to the except block that handles that exception type.
When working with files, a common error to handle is the ‘FileNotFoundError
‘. Here’s how to handle it:
try:
with open('non_existent_file.txt', 'r') as f:
print(f.read())
except FileNotFoundError:
print('The file could not be found.')
In this example, if the file does not exist, Python will throw a FileNotFoundError
. The except block catches this exception and prints a message saying ‘The file could not be found.’ instead of stopping the program.
It’s good practice to handle exceptions at the point where you have the information to deal with them appropriately. For example, if a function is responsible for reading a file and processing its contents, that function should handle any file-related exceptions because it knows what files it’s dealing with and what errors might arise.
In some cases, you may want to do something when an exception occurs and then re-raise the exception. You can do this with the ‘raise’ statement:
try:
with open('non_existent_file.txt', 'r') as f:
print(f.read())
except FileNotFoundError:
print('The file could not be found.')
raise
Here, if the file doesn’t exist, Python will print a message and then re-raise the FileNotFoundError
, allowing it to be caught and handled at a higher level in your code.
Best Practices to Avoid ‘File Not Found Error’
1. Check If File Exists Before Opening It:
We can use the os.path
module to check if the file exists before trying to open it can prevent a ‘File Not Found Error. Here’s an example:
import os
file_path = 'my_file.txt'
if os.path.isfile(file_path):
with open(file_path, 'r') as f:
print(f.read())
else:
print('The file does not exist.')
In this code, os.path.isfile(file_path)
returns True
if the file exists and False
otherwise.
2. Use Absolute Paths Instead of Relative Paths:
While it’s not always possible, using absolute paths can prevent errors due to confusion about the current working directory. If you need to use relative paths, make sure you know what the current working directory is. You can use os.getcwd()
to check the current working directory.
A relative path is a path that starts from the current working directory. For instance, if the current working directory is /home/user/documents
, and there’s a file named my_file.txt
within this directory, you can open this file with the relative path like this:
with open('my_file.txt', 'r') as f:
print(f.read())
An absolute path is a path that starts from the root directory. It is a complete path to the location of a file or a directory in a file system. The absolute path to the file in the previous example would be /home/user/documents/my_file.txt
. You can open the file with the absolute path like this:
with open('/home/user/documents/my_file.txt', 'r') as f:
print(f.read())
3. Handle File Paths Carefully:
File paths can be a source of errors, especially on systems where the path separator varies (like /
on Unix-based systems and \
on Windows). You can use os.path.join()
to create file paths in a platform-independent way:
import os
file_path = os.path.join('my_directory', 'my_file.txt')
4. Ensure Proper File Permissions:
If your program needs to read or write files, make sure it has the necessary permissions to do so. This might mean running the program with a different user or modifying the file permissions.
In order to read, write, or execute a file in Python, the program must have the necessary file permissions. If the program lacks the permissions to perform the requested operation, Python will raise a PermissionError
.
You can handle this exception in a try
—except
block. Here’s an example:
try:
with open('restricted_file.txt', 'w') as f:
f.write('Hello, World!')
except PermissionError:
print('Permission denied. Please check if you have the correct permissions to write to this file.')
In this example, Python tries to open a file named ‘restricted_file.txt’ in write mode and write ‘Hello, World!’ to it. If the program doesn’t have the necessary permissions to perform this operation, it will raise a PermissionError
, and the except
block will catch this exception and print a message to inform the user.
5. Check File Type Before Accessing:
Python’s os
module provides the os.path
module which can be used to perform such checks. Here’s a simple example:
import os
file_path = 'my_file.txt'
if os.path.isfile(file_path):
print('Regular file')
with open(file_path, 'r') as f:
print(f.read())
elif os.path.isdir(file_path):
print('Directory')
# perform directory operations here
elif os.path.islink(file_path):
print('Symbolic link')
# perform symbolic link operations here
else:
print('Unknown file type')
# handle other file types here
In this code:
os.path.isfile(file_path)
checks if the path is a regular file.os.path.isdir(file_path)
checks if the path is a directory.os.path.islink(file_path)
checks if the path is a symbolic link.
Each of these functions returns True if the path is of the corresponding type, and False otherwise. You can use these checks to determine the file type and handle each type accordingly.
Summary
In this article, we explored Python’s ‘File Not Found Error’, an exception raised when the Python interpreter can’t find a file that the code is attempting to open or manipulate. This error can occur due to a variety of reasons: the file doesn’t exist, the file is in a different location, the file is not a regular file (like a symbolic link, directory, or other non-regular file types), or the program doesn’t have the necessary permissions to access the file.
We also examined the concept of exception handling in Python, specifically focusing on how the ‘File Not Found Error’ can be gracefully handled using try-except blocks. This method allows the program to continue running even when such an error occurs, enhancing the robustness of the Python code.
Several scenarios were discussed with code snippets to illustrate instances where the ‘File Not Found Error’ may be encountered. In particular, these scenarios highlighted the differences between absolute and relative file paths and the implications of incorrect file paths or non-existent directories.
Finally, we discussed a variety of tips and tricks to avoid encountering the ‘File Not Found Error’. These include checking if a file exists before trying to open it using the os.path module, using absolute paths instead of relative paths when possible, careful handling of file paths, ensuring proper file permissions, and handling errors in a graceful manner.
Key Takeaways
- ‘File Not Found Error’ in Python is a common exception that can be avoided and handled with the right approaches.
- Using exception handling (try-except blocks), we can catch and manage these exceptions effectively to prevent the program from crashing.
- Checking the file or directory’s existence and type before trying to open it can help avoid this error.
- Ensuring correct use of absolute and relative paths and verifying proper file permissions are crucial steps.
- Even with precautions, errors can still occur. It’s essential to code in a way that gracefully handles potential exceptions and minimizes their impact.
- Understanding the nature of ‘File Not Found Error’ and the strategies to handle it will lead to the development of more robust and reliable Python programs.
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 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.