Python provides different methods and ways to check if a file exists. If the specified file exists the method returns True
boolean value if not it returns False
. In this tutorial, we examine how to check if a file exists in Python.
Check File Existence with os.path.exists() Method
The exists()
or os.path.exists()
method can be used to check if the specified file exists currently. The exists() method is provided by the os module and it should be imported before using the exists() method. In the following example, we check if the file “names.txt” exists in the current working directory. As we only provide the file name and do not provide a complete path the current working directory is checked for the specified file existance.
import os
print(os.path.exists("names.txt"))
True
As the result is True it means the “names.txt” file exists in the current working directory. We can also specify the complete or absolute path with the file name in order to make the check more reliable. In the following example, we check the “names.txt” file existence in the path “/home/ismail” by providing “/home/ismail/names.txt“.
import os
print(os.path.exists("/home/ismail/names.txt"))
Check File Existence with os.path.isfile() Method
Another alternative way to check file existence is using the isfile()
or os.path.isfile()
method. The isfile() method is provided by the os Module. The isfile() method is created to check if the specified path is a file or not. We can use it to check if the specified file exists too. In the following example we check if the “names.txt” file exists for the current working directory.
import os
print(os.path.isfile("names.txt"))
True
The result is true as the “names.txt” file exists and a file. Alternatively, we can specify the complete or absolute path in order to make the check more reliable. We provide “/home/ismail/names.txt” as a parameter to the isfile() method to check if the “names.txt” file exists in the “/home/ismail” ppath.
import os
print(os.path.isfile("/hme/ismail/names.txt"))
Check File Existence with pathlib.Path() Method
The Path()
or pathlib.Path()
method can be also used to check if the specified file exists. The pathlib module should be imported. The pathlib module is provided after Python 3.4. If you are using previous versions of Python it can not be used. In the following example, we check if the file “names.txt” file exists.
import pathlib
file = pathlib.Path("names.txt")
print(file.exists())
True
The output is “True” as the “names.txt” file exists. Alternatively, we can provide the absolute or complete path for the file to make things more reliable way.
import pathlib
file = pathlib.Path("/home/ismail/names.txt")
print(file.exists())