While working with the files or directories sometimes we need to apply a check function that checks whether the specific file or directory exists or not. In Python there are many built-in functions to check this. Following are some functions to check whether the file exists or not.
- os.path.exists() (is used for both file or directory)
- os.path.isfile()
- os.path.isdir()
- pathlibPath.exists()
Let’s take a look at them one by one.
os.path.exists()
This function returns true if the file exists else it returns false. Let’s take a look at code.
We need to import the os.path module to use the exist function.
import os.path from os import path |
Let’s take a look when the file exists.
import os.path from os import path print(path.exists(“secondFile.py”)) |
When the file is not present the following will be the output.
os.path.isfile()
We can utilise the isfile command to verify whether a provided input is a file or not.
import os.path from os import pathprint (path.isfile(‘secondFile.py’)) |
os.path.isdir()
If you want to verify that a given path leads to a directory, we can utilise the os.path.dir() function. Let’s take a look at the code.
In the code below, we are trying to access the file rather than a directory that’s why it is returning false.
import os.path from os import path print (path.isdir(‘secondFile.py’)) |
When we will try to access the folder then it will return true.
pathlibPath.exists()
We can also use the pathlib.exist() function to check both the file and directory. Let’s take a look at the code.
import pathlib file = pathlib.Path(“secondFile.py”) if file.exists (): print (“File exist”) else: print (“File not exist”) |
The following is the output.