python

How to check if a file or a directory exists in Python

In this tutorial, we are going to see some techniques in Python to check if a file or a directory exists or not.
 

Check if a path exists

Python’s ‘os’ module provides the function os.path.exists(path) which allows to check if a given path exists or not. It returns True if the path exists otherwise it returns False. The parameter ‘path’ can be a relative or an absolute path. See the code below,

import os.path

path = '/home/wtlx/dir'
# Check if the path exists or not
if os.path.exists(path) :
    print("Path " , path, " exists")
else:
    print("Path " , path, " not exists")

Output:

Path /home/wtlx/dir exists

With os.path.exists(path) we can make sure that this path exists or not, but we cannot make sure if it is a file or a directory.
 

 

Check if a file exists

Python’s ‘os’ module provides the function os.path.isfile(path) to check if a given file exists or not. It will return True if the given path points to a file and it exists. See the code below,

import os.path

# Check if the file exists or not
if os.path.isfile('/home/wtlx/dir/file.txt'):
    print("File exists")
else:
    print("File not exists")

Output:

File exists

 

Check if a directory exists

Python’s ‘os’ module provides the function os.path.isdir(path) allowing to check if a given directory exists or not. It will return True if the specified path points to a directory and it exists. See the code below,

import os.path

# Check if the directory exists or not
if os.path.isdir('/home/wtlx/dir'):
    print("Directory exists")
else:
    print("Directory not exists")

Output:

Directory exists
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *