Check if file or directory exists in Python
In this article, we have presented the approach to check if file or directory exists in Python using os library.
Table of contents:
- Check if file or directory exists in Python
- Complete Code
Check if file or directory exists in Python
In UNIX systems like Linux, everything is considered a file. So, both a standard file and a directory is a file for UNIX system.
So, the process to check if a directory or file exists is same. We can use the os module of Python to check this. Import the os module.
import os
To check if a file in UNIX exist, we can use the function os.path.exists(). It will return true if the directory exists or else, it will return false.
if os.path.exists("directory1"):
print ("File or Directory exists")
else:
print ("File or Directory does not exist")
Complete Code
Following is the complete Python code to check if file or directory exists:
import os
if os.path.exists("directory1"):
print ("Directory exists")
else:
print ("Directory does not exist")
if os.path.exists("file.txt"):
print ("File exists")
else:
print ("File does not exist")
With this article at OpenGenus, you must have the complete idea of how to Check if file or directory exists in Python.