Check if File Exists
To check if a file exists in Python, we can import os
package and use os.path.isfile()
function of the os
package.
In this tutorial, we will learn how to check if a file at given path exists or not, using Python programming.
First we shall look into the syntax of os.path.isfile() function. Secondly, we shall look into examples, where we check if a file exists.
Syntax
The syntax of os.path.isfile() function is:
os.path.isfile(path)
os.path.isfile()
returns a boolean value of True
if the given path is an existing regular file. Or else, it returns False
.
Example
In the following Python program, we shall check if the file at path /Users/tutorialkart/Downloads/sample.txt
is present or not.
example.py
import os
path = '/Users/tutorialkart/Downloads/sample.txt'
if ( os.path.isfile(path) ):
print('file with given path exists')
else:
print('file with given path does not exist')
If the file with given path is present, then we get the following output.
Output
file with given path exists
If the file with given path is not present, then we get the following output.
Output
file with given path does not exist
Conclusion
In this Python Tutorial, we learned how to check if a file defined by given path is present or not, using os.path.isfile()
function.