Python os.path.exists() Method
The Python os.path.exists() method is used to check whether a specified path exists in the file system.
If the path exists, it can refer to any type of file system object, such as a regular file, directory, symbolic link, or special file. If the path does not exist or if there are permission issues preventing access to the path, the method returns False.
Syntax
Following is the basic syntax of the Python os.path.exists() method −
os.path.exists(path)
Parameter
This method accepts a string as a parameter representing the path that you want to check for existence.
Return Value
The method returns a boolean value "True" or "False". It returns True if the specified path exists in the file system, otherwise it returns False.
Example
In the following example, we are checking whether the file path "/home/lenovo/documents/file.txt" exists in the filesystem using the exists() method −
import os
file_path = "/home/lenovo/documents/file.txt"
exists = os.path.exists(file_path)
print("The result is:",exists)
Output
The output obtained is as follows −
The result is: True
Example
Here, we are checking whether the Windows file path "C:\Users\user\Documents\file.txt" exists in the filesystem using the exists() method −
import os
file_path = "C:\\Users\\user\\Documents\\file.txt"
exists = os.path.exists(file_path)
print("The result is:",exists)
Output
Following is the output of the above code −
The result is: True
Example
In this example, we are checking whether the given symbolic link path "link_path" exists in the filesystem using the exists() method −
import os
link_path = "/home/lenovo/symlink"
exists = os.path.exists(link_path)
print("The result is:",exists)
Output
The result produced is as shown below −
The result is: True
Example
This example shows that if the given path is non-existent, the exists() method returns False −
import os
path = "/non/existent/path"
exists = os.path.exists(path)
print("The result is:",exists)
Output
We get the output as shown below −
The result is: False