Python check if file exists - How do I check if directory exists in Python?

Updated by shortbuzz

Python logo with folder icon and python code on computer screen in the background

In this article, we will learn "How to Check if a File Exists and How to Check if a Directory Exists in Python." and "How to Check If a File Is a Symlink in Python?" and "How do I check whether the specified path is an existing regular file or not?" and "How to check whether the specified path is an existing directory or not?" and "How to Check if Directory is empty or Not in Python?" and "How to Check if a File or Directory Exists in Python 3.4"

How do I check in Python if a file or directory exists, and whether the given path is a regular file or not?

Import the os.path module in your code.
To begin, we must import the os.path module. We gain access to functionality from an os.path module by importing the function using import. Now you can use os.path.exists(path), os.path.isfile(path), os.path.isdir(directory)

These methods return a Boolean value of type bool. These functions return True if the path exists; otherwise, they return False.

import os.path from os import path

How do I check if file exists and How to check if a directory exists in Python?

Method 1: To check if a given file or directory exists, use the os.path.exists() method in python
The os.path.exists(path) function in python is used to determine if a given file or directory exists or not; if it exists, it returns true. If it does not exist, return False.

The python code to verify whether a file or folder exists is shown below.
os.path.exists("your_file.txt")

How to check if file is a symlink in Python?

Method 2: To check whether the given symlink exists, use os.path.lexists() in python
The os.path.lexists()function in Python is used to determine whether or not the provided path exists. Unlike the os.path.exists() function, it returns True when a symbolic link (also symlink or soft link) is broken.

On platforms where os.path.lstat() is not supported, this function works similarly to os.path.exists().

How to validate a url in Python? below is the python code
path.lexists(link)

This python method returns a Boolean value. If the URL exists, this function returns True; otherwise, it returns False. For broken symbolic hyperlinks, it will return True.

The only difference between "os.path.lexists" and "os.path.exists" is that although lexists returns True in the case of broken symbolic links, exists returns False in that circumstance.

How do I check whether the specified path is an existing regular file or not?

Method 3: To determine if a given input is a file or not, use the os.path.isfile() method in python
In Python, we can check whether a given input is a file by using the os.path.isfile(path) function; if it is, it returns true; if it is not, it returns false.

The following Python code determines if the provided input is a file or not.
os.path.isfile('your_file.txt')

How to check whether the specified path is an existing directory or not?

Method 4: To check whether the given input is a directory or not use os.path.isdir() in python
To determine whether or not a given input is a directory, we can use the os.path.dir(directory) function in Python.

The Python code below detects if the given input is a directory or not.
os.path.isdir('myDirectory')

How to check if directory is empty or not in Python?

The os.listdir() function is used to determine whether or not a directory is empty. To obtain a list of all the files and folders in the given directory, use the os.listdir() function of the os module.

import os
your_path = '/your/path'
if os.path.isdir(your_path):
    if not os.listdir(your_path):
        print("Directory is empty")
    else:    
        print("Directory is not empty")
else:
    print("The specified directory does not exist.")

However, the os.listdir() function may throw an error, for example, if the specified path is invalid. As a result, you must address this.

The complete code for the above explanation is provided below.


# Python program to explain os.path.exists(), path.isfile(), path.isdir() method 

import os.path
from os import path

def main():

     print("The input is a file: " + str(path.isfile("your_file_path.txt")))
     print("The input is a directory: " + str(path.isdir("your_directory")))
     print("The input is URL is broken: " + str(path.lexists("your_file_path.txt")))
     print ("The input file exists:"+str(path.exists('your_file_path.txt')))
     print ("The input directory exists:" + str(path.exists('your_directory')))

if __name__== "__main__":
     main()

Output

  • os.path.exists() – Returns True if the path or directory exists.
  • os.path.lexists() – For an existing path, it returns True. else, it returns False, for broken symbolic links, but exists returns False for that.
  • os.path.isfile() – If path is a file, it returns True.
  • os.path.isdir() – If the path is a directory, it returns True.

How to Check If a Directory or File Exists in Python 3.4 or above version?

In Python 3.4, we use the pathlibPath.exists() method
To manage file system paths, Python 3.4 and later include the Pathlib Module. Python uses an object-oriented method to determine whether a folder exists.

A Path object's is_dir() and exists() methods can be used to check wheather input is directory or given input is exists

Step 1: We need to import pathlib main class in your python code
import pathlib

Step 2: Create a Path class instance and assign your path to it.

yourPath='/home/your_folder/your_file.txt'
file=pathlib.Path(yourPath)

class pathlib.Path(YourPath): A PosixPath or a WindowsPath is created when this class is instantiated. It is a subclass of PurePath and represents concrete paths of the system's path flavour:

step 3: In Python 3.4, check if the input path points to an existing file or directory.
print(file.exists())

The full code for whether or not the directory exists is provided below.

import pathlib
file = pathlib.Path("your_file.txt")
if file.exists ():
    print ("Given file is exist")
else:
    print ("Given file is not exist")
  • pathlib.Path.exists() - Returns True if the specified path or directory exists. (On Python 3.4 and later version)

Reference: Python os.path documentation

More articles from shortbuzz

ecommece template tailwindcss text and businessman
Technology

Get Free TailwindCSS eCommerce Template: Build Online Store

TailwindCSS eCommerce template free: Take advantage of our template & boost your online store's sales with a visually stunning and user-friendly website design continue reading

OpenAI logo chatgpt
Technology

How to block ChatGPT from access the content of your website

By adding code to robots.txt, .htaccess or Nginx server, you can stop ChatGPT from access or crawl your website content that is being used for AI training data continue reading

Google sign-in button and Google logo
Technology

How to migrate from Google Sign-In API to Identity Services

Use Google Identity Services API to improve the user experience & security of your website. Replace old Google Sign-In API with new method: Full migration guide continue reading

flower with cards
Technology

TailwindCSS: Show More/Less Truncate Text using JS & Reactjs

Use TailwindCSS, JavaScript or ReactJS to create a read more & show less function with a smooth transition using tailwind multi-line-clamp truncation continue reading

Convert Number to Words
Technology

Convert Number to Words using Javascript, Jquery, ReactJS

Code and output for Convert number to words using JQuery, ReactJS, JavaScript, and TypeScript. Example: convert 1 to one continue reading

cloud server with laptop
Technology

Best web hosting service provider in Saudi Arabia (KSA)

Find the best web hosting service providers for your company in Saudi Arabia. Our detailed list includes the most cost-effective, reliable, and fast options. continue reading

Web hosting server and cloud hosting server
Technology

What is Web Hosting and Types: A Complete Beginners Guide

For creation of websites requires web hosting. Learn about many types and their advantages and disadvantages to select the best option for your website. continue reading

Using tailwind css align item in the centre of the screen text and tailwind logo
Technology

Tailwind CSS center div vertically and horizontally

Using tailwindCSS, place the div in the middle of the screen, both vertically and horizontally, using flexbox or grid system with simple explanation. continue reading

Xampp error windows
Technology

How to fix Error: MySQL shutdown unexpectedly in XAMPP

The cause of "Error: MySQL Shutdown Unexpectedly" in XAMPP, shutting down MySQL without running XAMPP as an administrator frequently leads to corruption. continue reading

Bootstrap icon and Tailwind css icon and grid layout design
Technology

How to make Tailwind CSS grid system like Bootstrap grids

Tailwind offers grid-template-column utility for creating basic grids, as well as the grid-cols-{size} & col-span-{size} utilities to create bootstrap-like grid continue reading