How to check if a file exists in python.
When we do certain actions on an existing file like, copy, delete, read or write, etc., first we should check whether that file exists or not. So in this tutorial, we will learn how to check a file exists or not using the OS module using python.
Python programming language provides an OS module, in which a user can directly interact with the operating system.
In the below examples we will use OS module methods isfile()
and exists()
method to check if a file exists or not. The isfile()
and exists()
function checks whether a specific file exists or not, it returns True if a file exists otherwise it returns False.
Example: FileNotFoundError
Let us try to open a file. If the specified file does not exist, it will raise a FileNotFoundError
error.
In the below example, first, we will list files that are present in the directory. We use the try-except block to avoid the error, if the file exists, it will print the file name otherwise, it will print the file not exists message.
import os
f=open("abc.txt")
print("File name:",f.name)
As we can see from the output, the specified file does not exist. So it throws a FileNotFoundError.
f=open("studytonight.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'
Example: Check if a file exists in Python
The below example shows how to check whether a file exists or not using the exists()
function of the os module.
import os
def check_file():
file_name=input("Enter File Name: ")
x= os.path.exists(file_name)
print(x)
if x==True:
print("File exists:",file_name)
else:
print("File does not exist:",file_name)
check_file()
Once we run the program we will get the following result.
Enter File Name: demo_1.txt
True
File exists: demo_1.txt
Example: Check a file exists or not using the isfile() Function
The below example shows how to check whether a file exists or not using the isfile()
function of the os module.
import os
def check_file():
file_name=input("Enter File Name: ")
x= os.path.isfile(file_name)
print(x)
if x==True:
print("File exists:",file_name)
else:
print("File does not exist:",file_name)
check_file()
Once we run the program we will get the following result.
Enter File Name: demo_1.txt
True
File exists: demo_1.txt
Enter File Name: abc.txt
False
File does not exist: abc.txt
Conclusion
In this tutorial, we learned how to check if a file exists or not using the functions of the os module. We check the file exists or not using the isfile() function and exists() function.