The os
module in the standard library includes the path
sub-module which provides useful functions for working with and manipulating paths.
The exists()
function in the path
module is used to check whether a given path exists or not. It returns a Boolean value: True
if the path exists and False
otherwise.
To use the function in our programs, we will need to first import as shown below:
from os.path import exists
exist(p)
p |
A string representing the path to be tested. |
The function takes in a single argument, which is the path to the file/directory. The path maybe relative to the working directory or an absolute path. It returns a boolean value (True
/False
) depending on whether the path or file specified exists or not.
#on a Windows system
from os.path import exists
print(exists(r"C:\\"))
print(exists(r"C:\Users"))
print(exists(r"C:\Users\John\Desktop"))
True
True
True
In the above example, we tested the exists() function with some absolutes paths. As earlier mentioned, we can also use relative paths instead of absolute ones.
from os.path import exists
relative_paths = [r'\project', r'\images\me.jpg', r'music\taylor.mp3']
for p in relative_paths:
print(exists(p))
True
False
True
In the above example the function checks whether the relative paths exists. Obviously, running the above examples in your computer will return different results.
Note that in case of directory paths, the returned value will be the same regardless of whether a trailing slash is appended at the end of the pathname or not, so '/mypath' and '/mypath/' will be treated as equal.