23
How to check if a file exists in Python?
ItsMyCode |
When you perform a file operation such as reading from a file or writing content to a file, we need to check if a file or directory exists before doing the i/o operation.
There are different ways to check if a file exists in Python. Let’s take a look at each one of these in detail.
Using the OS module in Python, it’s easy to interact with Operating System. Currently, using OS module methods, we can verify easily if a file or directory exists.
- os.path.exists()
- os.path.isfile()
- os.path.isdir()
- pathlib.Path.exists()
The os.path.exists()
method checks both file and directory, and it returns true if a file or directory exists.
Syntax: os.path.exists(path)
# Example to check if file or directory exists in Python using the OS module
import os
print(os.path.exists("C:\Projects\Tryouts\etc\password.txt"))
print(os.path.exists("C:\Projects\Tryouts\etc"))
print(os.path.exists("C:\Projects\Tryouts\doesnotexists"))
# Output
True
True
False
The os.path.isfile()
method in Python checks whether the specified path is an existing regular file or not.
Syntax: os.path.isfile(path)
# Example to check if a file exists in Python using the OS module
import os
print(os.path.isfile("C:\Projects\Tryouts\etc\password.txt"))
print(os.path.isfile("C:\Projects\Tryouts\etc"))
print(os.path.isfile("C:\Projects\Tryouts\doesnotexists"))
# Output
True
False
False
The os.path.isdir()
method in Python is to check whether the specified path is an existing directory or not.
Syntax: os.path.isdir(path)
# Example to check if a directory exists in Python using the OS module
import os
print(os.path.isdir("C:\Projects\Tryouts\etc\password.txt"))
print(os.path.isdir("C:\Projects\Tryouts\etc"))
print(os.path.isdir("C:\Projects\Tryouts\doesnotexists"))
# Output
False
True
False
The pathlib
module is available in Python 3.4 and above. This module offers object-oriented classes filesystem paths with semantics appropriate for different operating systems.
Pathlib is the modern and most convenient way for almost all file or folder operations in Python, and it is easier to use.
Syntax: pathlib.Path.exists(path)
# Example to check if a file or directory exists in Python using the pathlib module
from pathlib import Path
file = Path("C:\Projects\Tryouts\etc\password.txt")
if file.exists ():
print ("File exist")
else:
print ("File not exist")
# Output
File exist
The post How to check if a file exists in Python? appeared first on ItsMyCode.
23