When you write Python scripts, you may want to perform certain actions, such as reading or writing to a file, only if the file exists.
There are multiple ways, you can do it in Python.
Setting the current working directory
If you use relative paths (file.txt) instead of absolute (d:/my_path/file.txt), be sure that the current working directory is set properly.
Check if a file exists
The simplest way to check if a file exists is to use the open() function.
If you try to open the file using this function, it either opens the file or returns an error if the file is not present at the specified location.
Let’s create a file (D:/file.txt).
Run this command:
It returns no error. That means that the file is present and accessible to a user.
If you run the same code with a path of a file that doesn’t exist, Python will return FileNotFoundError.
Of course, we can use handle this exception using try … except.
try: open('D:\\file_not_found.txt') except FileNotFoundError: print("File not found")
This code will return the following message.
File not found
The os.path module for checking if a file exists
Another way to check whether the file exists is to use the os.path module.
This module offers some methods which are used to do operations on file paths. They can be found under the functions provided by the module.
There are quite a few functions in the os.path module. In this tutorial, we are going to look at three of them: exists, isfile, and isdir.
os.path.exists(path) – Returns True if the path is either a file, directory, or a valid symlink.
os.path.isfile(path) – Returns True if the path is a file or a symlink to a file.
os.path.isdir(path) – Returns True if the path is a directory or a symlink to a directory.
The exists() function works for both files and directories:
import os.path if os.path.exists('d:\\file.txt'): print("File exists") if os.path.exists('d:\\existingdir'): print("Directory exists") else: print("File doesn't exist")
The isfile() function works only for files.
import os.path if os.path.isfile('d:\\file.txt'): print("File exists") else: print("File doesn't exist")
Using Python console
Instead of checking if a file exists directly from the script, you can do it from the terminal instead.
The command is going to look like this:
D:>python test.py file1.txt
I already wrote an article on this topic, so you can read it there.
Use name to find files with multiple extensions
Let’s check if a file exists using just a name without extension. For this task, we are going to use the glob function from the glob module. This code will return all existing files (with different extensions) that match the name.
This is the directory and file tree we are going to use to search for the files:
This code will return all files from D:\dir that start with the word “file”. We are going to use the wildcard character (*) in the following example.
import glob all_files = glob.glob('D:\\dir\\file*.*') print(all_files)
This code only works for the main directory.
['D:\\dir\\file2.txt', 'D:\\dir\\file3.txt', 'D:\\dir\\file4.rtf']
It won’t check whether the file exists in the subdirectory. For this, we are going to use the next script.
Using the os.path module to find files recursively
If we want to look for the file inside the main directory but also subdirectories, we can use one of the os methods called walk().
import os for root, dirs, files in os.walk("d:\\dir", topdown=False): for name in files: if 'file' in name: print(os.path.join(root, name))
If you run the code, you can see that it returns files names from the main directory, but also the “subdir” subdirectory. If the condition is met, the code will return all matching files.
d:\dir\subdir\file1.txt d:\dir\file2.txt d:\dir\file3.txt d:\dir\file4.rtf
The part of the code (if ‘file’ in the name) checks whether there is a string “file” inside the file name. You can also use different conditions:
|Function||What it does|
|startswith(‘file’)||Returns True if the string starts with “file”|
|endswith(‘file’)||Returns True if the string ends with “file”|
Checking if file exists in Python 3.4+
The pathlib module is a library that was introduced to Python in version 3.4.0 to provide common operations for manipulating files and directories as object paths instead of strings. The library is a powerful alternative to the built-in os.path, which provides a subset of the features provided by the pathlib module.
The pathlib module can be used to check whether a specific file exists.
from pathlib import Path if Path('d:\\file.txt').is_file(): print("File exists") else: print("File doesn't exist")
The code returns the following text:
This table compares the functions from both modules.
|check for file or directory||os.path.exists(path)||pathlib.Path(path).exists()|
|check for file||os.path.isfile(path)||pathlib.Path(path).is_file()|
|check for directory||os.path.isdir(path)||pathlib.Path(path).is_dir()|
In this tutorial, you have learned how to check whether single or multiple files exist using a few different methods, some of them available only in the newer versions of Python.