Example of how to check if path to a file or a directory exists in python
Checking if path to a file or a directory exists using os.path.exists()
Let consider for example the following path to a file called photo_001.png:
/users/john/images/photo_001.png
to check if the path exists a solution is to use os.path.exists()
import os
os.path.exists('/users/john/images/photo_001.png')
will returns
True
or
False
if the path exists or not respectively.
It also works if it is a path to a directory:
/users/john/images
the
os.path.exists('/users/john/images')
returns
True
only if the path /users/john/images exists.
Checking if it is a path to a file
The function os.path.exists() tells you if the path exists, but not if it is a file or a directory.
To check if it is a file, a solution is to use isfile:
For example (assuming that '/users/john/images/photo_001.png' exists)
os.path.isfile('/users/john/images/photo_001.png')
will returns
True
but
os.path.isfile('/users/john/images')
will returns
False
since it is a directory and not a file.
So a common usage is to check forst is a pth exists and then to check if it is a file:
if os.path.exists( "/users/john/images/photo_001.png"):
if os.path.isfile('/users/john/images/photo_001.png'):
print('File found !')
Checking if it is a path to a directory
To check if it is a directory, a solution is to use isdir
For example (assuming that '/users/john/images' exists)
os.path.isdir('/users/john/images')
will returns
True
but
os.path.isdir('/users/john/images/photo_001.png')
will returns
False
since it is a file and not a directory
How to get a list of files and directories available under a given path
To get a list of files and directories available under a given path for example '/users/john/' a solution is to use os.listdir():
os.path.listdir('/users/john/')