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:
How to Create Directory If it Does Not Exist using Python?
Next article icon

Python – How to Check if a file or directory exists

Last Updated : 24 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Python about How to check if a file already exists in Python. We will cover four methods to check if a file or directory is already present.

How to check if a File or Directory Exists in Python?

To check if a file or directory already exists in Python, you can use the following methods:

  1. os.path.exists(path): Checks if a file or directory exists at the given path.
  2. os.path.isfile(path): Checks if a file exists at the given path.
  3. os.path.isdir(path): Checks if a directory exists at the given path.
  4. pathlib.path.exists(): Checks if the represented file or directory exists (part of the Pathlib object).

Using os.path.exists() to Check if a File or Directory Exists

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.

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

Syntax: os.path.exists(path)

Parameter: 

  • path: A path-like object representing a file system path. 

Return:  Returns TRUE if the path exists else FALSE.

Example: Checking if a path exists using os.path.exists()

Python3
import os     # Specify path  path = '/usr/local/bin/'    # Check whether the specified  # path exists or not  isExist = os.path.exists(path)  print(isExist)        # 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() Method to Check if the File Exists

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

Syntax: os.path.isfile(path)

Parameter: 

  • path: A path-like object representing a file system path. 

Return Type: Returns TRUE if file exits, else FALSE

Example: Checking if a path pointing to a resource is a file

Python3
import os  # Path  path = 'C:/Users/gfg/Desktop/file.txt'  # Check whether a path pointing to a file isFile = os.path.isfile(path) print(isFile)  # Path path = '/home/User/Desktop/'  # Check whether the path is a file isFile = os.path.isfile(path) print(isFile) 

Output: 

True False

Using os.path.isdir() Method to Check if Directory Exists

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.

Syntax: os.path.isdir(path)

Parameter: 

  • path: A path-like object representing a file system path.

Return Type: Returns TRUE if directory exists, else FALSE

Example 1: Check if a path is a directory using os.path.isdir()

Python3
import os.path     # Path  path = '/home/User/Documents/file.txt'    # Check whether the path is an existing directory isdir = os.path.isdir(path)  print(isdir)        # Path  path = '/home/User/Documents/'    # Check whether the path is a directory isdir = os.path.isdir( 


Output: 

False True  

Example 2: If the specified path is a symbolic link.

Python3
import os.path       # Create a 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     # Check whether the specified path is an  # existing directory or not  isdir = os.path.isdir(path)  print(isdir)     path = symlink_path     # check whether the symlink is  # an existing directory or not isdir = os.path.isdir(path)  print(isdir)  

Output: 

True True

Using pathlib.Path.exists() to Check if the File or Directory Exists

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 pathlib module are divided into pure paths and concrete paths. Pure paths provide only computational operations but do not provide I/O operations, while concrete paths inherit from pure paths to provide computational as well as I/O operations.

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

Syntax: pathlib.Path.exists(path)

Parameter: 

  • path: A path-like object representing a file system path.

Return Type: Returns TRUE if  file or directory exists, else FALSE 

Example: Check if the path exists using pathlib module

Python3
# Import Path class from pathlib import Path  # Path path = '/home/tuhingfg/Desktop'  # Instantiate the Path class obj = Path(path)  # Check if path exists print("path exists?", obj.exists()) 

Output: 

True

In this tutorial, we have covered 4 methods on how to check if a  file or directory already exists in Python. We have covered the use of OS module and pathlib module with their respective functions like os.path.isfile(), os.path.isdir(), pathlib.path.exists(), etc. These are some of the easiest methods you can try to check if the file already exists in Python.



Next Article
How to Create Directory If it Does Not Exist using Python?

N

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

Similar Reads

  • How to check whether a file exists without exceptions?
    When working with files in Python, it’s often necessary to check if a file exists before attempting to read from or write to it. While exception handling using try and except blocks is a common approach, Python provides cleaner and more intuitive methods to achieve this. In this article, we will exp
    2 min read
  • How to Create Directory If it Does Not Exist using Python?
    In this article, We will learn how to create a Directory if it Does Not Exist using Python. Method 1: Using os.path.exists() and os.makedirs() methods Under this method, we will use exists() method takes path of demo_folder as an argument and returns true if the directory exists and returns false if
    2 min read
  • How to check if a Python variable exists?
    Checking if a Python variable exists means determining whether a variable has been defined or is available in the current scope. For example, if you try to access a variable that hasn't been assigned a value, Python will raise a NameError. Let’s explore different methods to efficiently check if a va
    4 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
  • How to Get directory of Current Script in Python?
    A Parent directory is a directory above another file/directory in a hierarchical file system. Getting the Parent directory is essential in performing certain tasks related to filesystem management. In this article, we will take a look at methods used for obtaining the Parent directory of the current
    4 min read
  • How to check if a deque is empty in Python?
    In this article, we are going to know how to check if a deque is empty in Python or not. Python collection module provides various types of data structures in Python which include the deque data structure which we used in this article. This data structure can be used as a queue and stack both becaus
    3 min read
  • How to iterate over files in directory using Python?
    Iterating over files in a directory using Python involves accessing and processing files within a specified folder. Python provides multiple methods to achieve this, depending on efficiency and ease of use. These methods allow listing files, filtering specific types and handling subdirectories. Usin
    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 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
  • How to check if a csv file is empty in pandas
    Reading CSV (Comma-Separated Values) files is a common step in working with data, but what if the CSV file is empty? Python script errors and unusual behavior can result from trying to read an empty file. In this article, we'll look at methods for determining whether a CSV file is empty before attem
    4 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