28
loading...
This website collects cookies to deliver better user experience
os.path.exists()
method checks both file and directory, and it returns true if a file or directory exists.# 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
os.path.isfile()
method in Python checks whether the specified path is an existing regular file or not.# 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
os.path.isdir()
method in Python is to check whether the specified path is an existing directory or not. # 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
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.# 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