In Python, you can easily check whether a file or directory exists using the os.path.exists()
method from the os
standard library module. This method returns True
if the specified file or directory exists, and False
otherwise.
Here is an example showcasing how to use os.path.exists()
to check the existence of a file:
import os
filename = '/Users/flavio/test.txt'
exists = os.path.exists(filename)
print(exists) # True
In the above code, we import the os
module and assign the file path ‘/Users/flavio/test.txt’ to the filename
variable. Then, we call the os.path.exists()
method with the filename
variable as the argument. The method returns True
if the file exists and False
if it doesn’t. We assign the result to the exists
variable.
Finally, we print the value of the exists
variable, which determines whether the file exists in the specified file path. In this case, the output will be True
if the file exists.
Please note that the os.path.exists()
method can be used to check the existence of both files and directories. If you pass a directory path to the method, it will return True
if the directory exists and False
if it doesn’t.
Tags: Python, file existence, directory existence