Skip to main content

Python Check If File Exists

When processing files, it's a best practice to check if files exist before doing something else with them (such as read, write, delete)

Check If File Exists

To check if a file exists, you can use the exists() function from the os.path module or is_file() method from the Path class in the pathlib module.

Using os.path.exists() method

To check if a file exists, you pass the file path to the exists() function from the os.path standard library.

import os.path

os.path.exists(path_to_file)

If the file exists, the exists() function returns True. Otherwise, it returns False.

For example, check if test.txt file exists in the same folder:

import os.path

file_exists = os.path.exists('test.txt')
print(file_exists)

and if the test.txt file exists it will print True, otherwise False.

Using the pathlib module

Python introduced the pathlib module since the version 3.4.

The pathlib module allows you to manipulate files and folders using the object-oriented approach.

from pathlib import Path

path = Path(path_to_file)
file_exists = path.is_file()

Explanation:

  • First, import the Path class from the pathlib module.
  • Then, instantiate a new instance of the Path class and initialize it with the file path that you want to check for existence.
  • Finally, check if the file exists using the is_file() method.
note

If the file does not exist, the is_file() method returns False. Otherwise, it returns True

For example, use pathlib module to check if the file test.txt exists in the same folder of the program:

from pathlib import Path

path_to_file = 'readme.txt'
path = Path(path_to_file)

if path.is_file():
print(f'The file {path_to_file} exists')
else:
print(f'The file {path_to_file} does not exist')

and if the test.txt file exists it will print The file test.txt exists, otherwise The file test.txt does not exist.