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

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:

Summary

Here is a summary in a tabular form:

FeaturePython 2.xPython 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

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *