Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - List Files in a Directory
Next article icon

Check if a File or Directory Exists in Python

Last Updated : 04 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

To check how to check if a Directory Exists without exceptions in Python we have the following ways to check whether a file or directory already exists or not.

Table of Content

  • OS Module
    • Using os.path.exists()
    • Using os.path.isfile()
    • Using os.path.isdir()
  • Pathlib Module
    • Using pathlib.Path.exists()

OS Module

OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system-dependent functionality. os.path module is a submodule of the OS module in Python used for common path name manipulation.

Using os.path.exists()

The os.path.exists() method in Python is used to check whether the specified path exists or not. This method can be also used to check whether the given path refers to an open file descriptor or not. 

Python
import os  # Example 1 # Specify path path = '/usr/local/bin/'  # Check whether the specified path exists or not isExist = os.path.exists(path) print(isExist)  # Example 2 # Specify path path = '/home/User/Desktop/file.txt'  # Check whether the specified path exists or not isExist = os.path.exists(path) print(isExist) 

Output
True False

Using os.path.isfile()

os.path.isfile() method in Python is used to check whether the specified path is an existing regular file or not.

Python
# importing os module import os  # Path path = 'C:/Users/gfg/Desktop/file.txt'  # Check whether the specified path is # an existing file isFile = os.path.isfile(path) print(isFile)  # Path path = '/home/User/Desktop/'  # Check whether the specified path is # an existing file isFile = os.path.isfile(path) print(isFile) 

Output: 

True
False

Using os.path.isdir()

os.path.isdir() method in Python is used to check whether the specified path is an existing directory or not. This method follows a symbolic link, which means if the specified path is a symbolic link pointing to a directory then the method will return True.

Example 1: Python program to explain os.path.isdir() method.

Python
# importing os.path module import os.path  # Path path = '/home/User/Documents/file.txt'  # Check whether the specified path is an # existing directory or not isdir = os.path.isdir(path) print(isdir)  # Path path = '/home/User/Documents/'  # Check whether the specified path is an # existing directory or not isdir = os.path.isdir(path) print(isdir) 

Output: 

False
True

Example 2: Python program to explain os.path.isdir() method, If the specified path is a symbolic link.

Python
# importing os.path module import os.path  # Create a directory # (in current working directory) dirname = "GeeksForGeeks" os.mkdir(dirname)  # Create a symbolic link # pointing to above directory symlink_path = "/home/User/Desktop/gfg" os.symlink(dirname, symlink_path)  path = dirname  # Now, Check whether the specified path is an # existing directory or not isdir = os.path.isdir(path) print(isdir)  path = symlink_path  # Check whether the specified path (which is a symbolic link)  # is an existing directory or not isdir = os.path.isdir(path) print(isdir) 

Output: 

True
True

Pathlib Module

Pathlib module in Python provides various classes representing file system paths with semantics appropriate for different operating systems. This module comes under Python’s standard utility modules. Path classes in the Pathlib module are divided into pure paths and concrete paths. Pure paths provide only computational operations but do not provides I/O operations, while concrete paths inherit from pure paths provide computational as well as I/O operations.

Using pathlib.Path.exists()

The pathlib.Path.exists() method is used to check whether the given path points to an existing file or directory or not. 

Python
# Import Path class from pathlib import Path  # Path path = '/home/gfg/Desktop'  # Instantiate the Path class obj = Path(path)  # Check if path points to # an existing file or directory print(obj.exists()) 

Output: 

True

If you’re searching in current directory or below, to find the folder, use ./  before  folder name or it’ll give wrong result.

Python
import os  print(os.path.isdir('./my_folder')) # print true or false if my_folder exist or not in current directory   print(os.path.isdir('./Folder/search_folder')) #will tell if search_folder exist or not inside Folder 


Next Article
Python - List Files in a Directory

N

nikhilaggarwal3
Improve
Article Tags :
  • Python
  • Python file-handling-programs
  • Python OS-path-module
  • python-file-handling
Practice Tags :
  • python

Similar Reads

  • Python - How to Check if a file or directory exists
    Sometimes it's necessary to verify whether a dictionary or file exists. This is because you might want to make sure the file is available before loading it, or you might want to prevent overwriting an already-existing file. In this tutorial, we will cover an important concept of file handling in Pyt
    5 min read
  • Check if a string exists in a PDF file in Python
    In this article, we'll learn how to use Python to determine whether a string is present in a PDF file. In Python, strings are essential for Projects, applications software, etc. Most of the time, we have to determine whether a string is present in a PDF file or not. Here, we'll discuss how to check
    2 min read
  • Python - List Files in a Directory
    Sometimes, while working with files in Python, a problem arises with how to get all files in a directory. In this article, we will cover different methods of how to list all file names in a directory in Python. Table of Content What is a Directory in Python?How to List Files in a Directory in Python
    9 min read
  • Check if element exists in list in Python
    In this article, we will explore various methods to check if element exists in list in Python. The simplest way to check for the presence of an element in a list is using the in Keyword. Example: [GFGTABS] Python a = [10, 20, 30, 40, 50] # Check if 30 exists in the list if 30 in a: print("Eleme
    3 min read
  • Listing out directories and files in Python
    The following is a list of some of the important methods/functions in Python with descriptions that you should know to understand this article. len() - It is used to count number of elements(items/characters) of iterables like list, tuple, string, dictionary etc. str() - It is used to transform data
    6 min read
  • Check if a list is empty or not in Python
    In article we will explore the different ways to check if a list is empty with simple examples. The simplest way to check if a list is empty is by using Python's not operator. Using not operatorThe not operator is the simplest way to see if a list is empty. It returns True if the list is empty and F
    2 min read
  • Python | Move or Copy Files and Directories
    Let's say we want to copy or move files and directories around, but don’t want to do it by calling out to shell commands. The shutil module has portable implementations of functions for copying files and directories. Code #1 : Using shutil module import shutil # Copy src to dst. (cp src dst) shutil.
    3 min read
  • Python - List files in directory with extension
    In this article, we will discuss different use cases where we want to list the files with their extensions present in a directory using python. Modules Usedos: The OS module in Python provides functions for interacting with the operating system.glob: In Python, the glob module is used to retrieve fi
    3 min read
  • Check if directory contains files using python
    Finding if a directory is empty or not in Python can be achieved using the listdir() method of the os library. OS module in Python provides functions for interacting with the operating system. This module provides a portable way of using operating system dependent functionality. Syntax: os.listdir(
    3 min read
  • Get Current directory in Python
    In this article, we will cover How to Get and Change the Working Directory in Python. While working with file handling you might have noticed that files are referenced only by their names, e.g. 'GFG.txt' and if the file is not located in the directory of the script, Python raises an error. The conce
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences