Coding Triumph

Helpful code snippets & tutorials

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

Checking if a file or a directory exists with the Python language is straightforward; all you need is the os .path module and its built-in method exists().

Prerequisite:

  1. Python version 3
  2. exists() method

Method definition:

os.path.exists(path)
# "path": path to the file or directory
# returns True if path refers to an existing path 

The script:

import os

file = '/home/User/Desktop/test.txt'
dir = '/home/User/Desktop/'

fileExists = os.path.exists(file)
dirExists = os.path.exists(dir)

print(fileExists) # True
print(dirExists) # True
If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments