Check whether a file or directory exists in Python
Welcome to a new Python code snippet. In this post, we are going to learn how to check whether a file or directory (ex. file path) exists using Python. A common use case is to check if a file exists before opening for reading or writing. Let us take some examples…
Check file exists in current directory
We can use Python 2.x standard library os.path module:
- The function isfile() returns True if the input path points to an existing file
- The function isdir() returns True if the input path points to an existing directory
- The function exists() returns True if the input path exists whether it is a file or directory
1 2 3 4 5 6 7 8 9 10 11 |
import os # Prints True if 1.txt is a file in current directory print os.path.isfile('1.txt') # Prints True if /path/to/dir is a directory # Prints False otherwise or if it does not exist print os.path.isdir('/path/to/dir') # Prints True if 1.txt exists. This applies to both # files and directories print os.path.exists('1.txt') |
Check file exists – wildcard or regular expression
If you want to use regular expressions or wildcards, you may check the following code snippets. There are a couple of methods to achieve that (ex. glob module, etc)
Check file exists with extension
Similarly, if you want to check for files with specific extension, you may also check the same code snippet.
What about case sensitivity ?
These built in functions assume case sensitive file names and paths, so you should take that into consideration.
Check file exists in Python 3.x
In Python 3.x, the syntax is more of an object oriented style. Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 |
from pathlib import Path # Prints True if 1.txt is a file in current directory print(Path('1.txt').is_file()) # Prints True if /path/to/dir is a directory # Prints False otherwise or if it does not exist print(Path('/path/to/dir/').is_dir()) # Prints True if 1.txt exists. This applies to both # files and directories print(Path('1.txt').exists()) |
Summary
Here is a summary in a tabular form:
Feature | Python 2.x | Python 3.x |
---|---|---|
is file ? | os.path.isfile('path/to/file') | Path('path/to/file').is_file() |
is directory ? | os.path.isdir('/path/to/dir') | Path('/path/to/dir/').is_dir() |
does it exist ? | os.path.exists('/some/path') | Path('/some/path').exists() |
References
Thanks for visiting. For questions and feedback, please use the comments section below