How to Check if a File Exists in Python

Checking if a file exists in Python has many uses, this could be to avoid errors when trying to open a file or for a condition to create a file if one doesn't exist. The easiest way to look for the presence of a file is to use the os package, which provides methods for this exact task.

 

In this tutorial, we will learn how to check if a file or a directory exists in Python using the os package.

 

Import the os Package path Method

You may already be using the os package, if not you only have to import the os.path class.

 

import os.path

 

Check if File Exists

To check if a file exists, use the path.isfile() method, passing the path to the file inside the () (parenthesis). It will return True if the file was found or False if not.

 

result = os.path.isfile('fruit.json')

print(result)
True

 

The path to the file will be relative to where your Python program runs from. Read more about how the file system works in Linux.

 

Since the result from path.isfile() is boolean it can be used with an if conditional statement to create a file if one doesn't exist.

 

path = 'new_dir/test.txt'
exists = os.path.isfile(path)

if result:
    some_content = 'this is some content'

    with open(path, 'w') as f:
        f.write(some_content)

    print('File created!')
File created!

 

Using open() with a try-except Block

Another way to check a file exists is to use open() function inside a try except block. This essentially says try opening a file and if that is not possible do something else.

 

try:
    f = open('test.txt')
    
    print('File found!')
    
except:
    print('File not found!')
File not found!

 

Check if Directory Exists

To check if a directory exists, use the path.isdir(), passing the path to the directory inside the () (parenthesis). It will return True if a directory with the given name exists or False if no match is found.

 

result = os.path.isdir('new_dir')

print(result)
True

 

Check Whether a File or a Directory Exists at a Path

It is possible to check if anything exists with a name at a given path, regardless of whether that thing is a directory or a file by using the path.exists() method. Like the previous methods, it will True if something is found with the given name and False if nothing is found.

 

result = os.path.exists('new_dir')

print(result)
True

 

Conclusion

You now know how to check if a file or a directory exists in Python and do something if it was or wasn't found.

file directory check

Related Tutorials