Handling Python FileNotFoundError

Python FileNotFoundError

If you have received the error “FileNotFoundError: [WinError 2] The system cannot find the file specified”, it means that there is no file present at the path you specified.

In this tutorial, we shall learn when this is thrown by a Python program, and how to handle this FileNotFoundError.

Recreate FileNotFoundError

Let us recreate this scenario where Python interpreter throws FileNotFoundError.

In the following program, we try to delete a file. But, we have provided the path which does not exist. Python understands this situation as file not present.

Python Program

import os

os.remove('C:\workspace\python\data.txt')
print('The file is removed.')

In the above program, we tried to remove a file present at the path C:\workspace\python\data.txt.

Console Output

C:\workspace\python>dir data*
 Volume in drive C is OS
 Volume Serial Number is B24

 Directory of C:\workspace\python

22-02-2019  21:17                 7 data - Copy.txt
20-02-2019  06:24                90 data.csv
               2 File(s)             97 bytes
               0 Dir(s)  52,524,586,329 bytes free

We don’t have the file that we mentioned in the path. So, when we run the program, the system could not find the file. And it throws FileNotFoundError.

Solution – Python FileNotFoundError

There are two ways in which you can handle FileNotFoundError.

  • Use try-except and handle FileNotFoundError
  • Check if file is present, and proceed with the file operation accordingly.

In the following program, we have used Python Try Except. We shall keep the code in try block, which has the potential to throw FileNotFoundError.

Python Program

import os

try:
    os.remove('C:/workspace/python/data.txt')
    print('The file is removed.')
except FileNotFoundError:
    print('The file is not present.')

Or, you can check if the provided path is a file. Following is an example program.

Python Program

import os

if os.path.isfile('C:/workspace/python/data.txt'):
    print('The file is present.')
else:
    print('The file is not present.')

Summary

In this tutorial of Python Examples, we learned how to handle or solve FileNotFoundError in Python.

Code copied to clipboard successfully 👍