The os.path.isfile() is a built-in Python method that returns True if the path is an absolute pathname.
Syntax
os.path.isfile(path)
Parameters
The os.path.isfile() function takes a path as a parameter representing an object representing a file system path. A path-like object is either a string or bytes object representing a path.
Return Value
The os.path.isfile() method returns a Boolean value of class bool. The os.path.isfile() method returns True if the specified path is an existing regular file. Otherwise, it returns False.
Example 1
Let’s define a folder path and pass that path to the isfile() function.
import os
path = "/Users/krunal/Desktop/code/pyt/database"
isFile = os.path.isfile(path)
print(isFile)
Output
False
You can see that we have passed the folder path and not the file path to the isfile() function; hence, it returns False.
Example 2
import os
path = "/Users/krunal/Desktop/code/pyt/database/app.py"
isFile = os.path.isfile(path)
print(isFile)
Output
True
To check if the file exists in the file system using Python, use the os.path.isfile() function. If you attempt to navigate or open a non-existent file, then this will cause an error.
That’s it.