Python - How to Check if a file or directory exists - GeeksforGeeks (2024)

Last Updated : 24 Apr, 2024

Summarize

Comments

Improve

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:

TrueFalse

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 fileisFile = os.path.isfile(path)print(isFile)# Pathpath = '/home/User/Desktop/'# Check whether the path is a fileisFile = os.path.isfile(path)print(isFile)

Output:

TrueFalse

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 directoryisdir = os.path.isdir(path) print(isdir) # Path path = '/home/User/Documents/' # Check whether the path is a directoryisdir = os.path.isdir(

Output:

FalseTrue

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

Python3
import os.path # Create a directorydirname = "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 notisdir = os.path.isdir(path) print(isdir) 

Output:

TrueTrue

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 classfrom pathlib import Path# Pathpath = '/home/tuhingfg/Desktop'# Instantiate the Path classobj = Path(path)# Check if path existsprint("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.



N

nikhilaggarwal3

Python - How to Check if a file or directory exists - GeeksforGeeks (1)

Improve

Next Article

Python: Check if a File or Directory Exists

Please Login to comment...

Python - How to Check if a file or directory exists - GeeksforGeeks (2024)

FAQs

Python - How to Check if a file or directory exists - GeeksforGeeks? ›

path. exists() to check if a file or directory exists using Python. We further use this method to check if a particular file path refers to an already open descriptor or not.

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

path. exists() to check if a file or directory exists using Python. We further use this method to check if a particular file path refers to an already open descriptor or not.

How to check if there is a file in a directory in Python? ›

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.

How do you check if a file exists and is readable in Python? ›

path. isfile` and `os. access`. If both conditions are met, it prints “File is readable.” Otherwise, if the file does not exist or is not readable, it prints “File is not readable.” This ensures a robust check for file accessibility before attempting further operations.

How do you check if a directory exists and not empty in Python? ›

listdir(dirname): ... In python os, there is a function called listdir , which returns an array of the files contents of the given directory. So if the array is empty, it means there are no files in the directory.

How do you check if a file exist and is a directory? ›

Method 1: Using the os.

exists() function is a straightforward way of checking the existence of a file or directory. It's simple to use and understand. Here, I use an if statement that returns “This file exists.” if the my_file. txt file is present in my_data , and ”This file does not exist” otherwise.

How to check if a directory exists or not? ›

Checking if a Directory Exists

isdir() function by passing the directory path as an argument. import os dir_path = "example_directory" if os. path. isdir(dir_path): print(f"{dir_path} exists.") else: print(f"{dir_path} does not exist.")

What is the command to check Python directory? ›

Method 1: Using Command Prompt (CMD)
  1. Step 1: Open Command Prompt. Press Win + R to open run window, type cmd, and press Enter.
  2. Step 2: Use the where Command. In the Command Prompt window, type the following command: where python. Press Enter, and the system will display the paths where Python is installed.
Aug 25, 2023

How do you identify a directory in Python? ›

There are a couple of ways to get the current working directory in Python:
  1. By using the os module and the os. getcwd() method.
  2. By using the pathlib module and the Path. cwd() method.
Mar 28, 2023

How to check if a file exists in terminal? ›

The -f flag tests whether the provided filename exists and is a regular file. To test for directories instead, we can use the -d flag. To test for both files and directories, we can use the -e flag. More information about test can be found on its manual page, accessible by typing man test into the terminal.

How do you keep checking if a file exists in Python? ›

The most common way to check for the existence of a file in Python is using the exists() and isfile() methods from the os. path module in the standard library.

How to check file exists and file size in Python? ›

os. path. getsize() will:
  1. os. path. getsize() will: Return the size, in bytes, of path. Raise OSError if the file does not exist or is inaccessible. ...
  2. whereas os. path. exists(path) will: Return True if path refers to an existing path or an open file descriptor. Returns False for broken symbolic links.
Feb 26, 2015

How do you check if a file exists or is empty in Python? ›

Using the os module

We can evaluate the existence of a file/directory by using the exists() method of the os. path module. For better filtering of our results, we can also use the isfile() and isdir() methods to know if the mentioned path leads to a file or a directory.

How do you make sure a directory exists in Python? ›

In Python, use the os. path. exists() method to see if a directory already exists, and then use the os. makedirs() method to create it.

How to check if a file is directory in Python? ›

Use os. path. isfile() , os. path. isdir() , or os. path. exists()
  1. path. isfile(path) : returns True if the path is a valid file.
  2. path. isdir(path) : returns True if the path is a valid directory.
  3. path. exists(path) : returns True if the path is a valid file or directory.

How do you check if there is nothing in a list Python? ›

A: No, Python does not have a built-in function specifically to check if a list is empty. However, you can use Python's built-in len() function or simply use the list in a boolean context to check if it's empty.

How do I check if a directory exists in Python bash? ›

Check if a Directory Exists in Bash

echo $? echo $? The command output is 0 , which means that the directory exists. The test command works the same as it does for files, so using brackets instead of the test command works here too.

How do I know which directory Python is installed? ›

Follow the steps below:
  1. Step 1: Open Terminal. You can open Terminal by searching for it in the Start menu and selecting "Terminal"
  2. Step 2: Use the Get-Command Command. In the Terminal window, type the following command: (Get-Command python).Path. Press Enter, and Terminal will reveal the paths where Python is installed.
Aug 25, 2023

How do you check if a file exists in a directory CMD? ›

Resolution
  1. Click Start, and click Run.
  2. In the Open field, type CMD. A command prompt window appears.
  3. Type edit test. ...
  4. Type :check_for_file_existence and press <Enter>.
  5. Type if exist c:\ftp\ftpfile. ...
  6. Type sleep 200 and press <Enter>. ...
  7. Type goto check_for_file_existence and press <Enter>.
  8. Type :perform and press <Enter>.

How to check if it is a file or directory in Linux? ›

Another method: ls -l displays the files and folders with permission bits. If the line starts with a -, it's a file, if it's a directory, it starts with a d.

Top Articles
Which assets are not depreciated? — AccountingTools
Why Is it So Hard to Get an American Express Credit Card?
The Daily News Leader from Staunton, Virginia
Richard Sambade Obituary
The Haunted Drury Hotels of San Antonio’s Riverwalk
Devourer Of Gods Resprite
Imbigswoo
Comenity Credit Card Guide 2024: Things To Know And Alternatives
Obituary Times Herald Record
Tight Tiny Teen Scouts 5
Gt Transfer Equivalency
Synq3 Reviews
Skylar Vox Bra Size
R/Afkarena
Jvid Rina Sauce
Tnt Forum Activeboard
Zoe Mintz Adam Duritz
Palm Springs Ca Craigslist
Hyvee Workday
Kashchey Vodka
Melendez Imports Menu
Dragonvale Valor Dragon
Like Some Annoyed Drivers Wsj Crossword
Yosemite Sam Hood Ornament
Cookie Clicker Advanced Method Unblocked
Wood Chipper Rental Menards
JVID Rina sauce set1
Black Panther 2 Showtimes Near Epic Theatres Of Palm Coast
Sandals Travel Agent Login
Obituaries, 2001 | El Paso County, TXGenWeb
Www Mydocbill Rada
Homewatch Caregivers Salary
Colin Donnell Lpsg
Sports Clips Flowood Ms
Flixtor Nu Not Working
Los Amigos Taquería Kalona Menu
Desirulez.tv
Serenity Of Lathrop - Manteca Photos
Indiana Wesleyan Transcripts
Jefferson Parish Dump Wall Blvd
Los Garroberros Menu
Kelly Ripa Necklace 2022
Tirage Rapid Georgia
The Minneapolis Journal from Minneapolis, Minnesota
Deshuesadero El Pulpo
Dispensaries Open On Christmas 2022
Cabarrus County School Calendar 2024
York Racecourse | Racecourses.net
15:30 Est
Lira Galore Age, Wikipedia, Height, Husband, Boyfriend, Family, Biography, Net Worth
786 Area Code -Get a Local Phone Number For Miami, Florida
Olay Holiday Gift Rebate.com
Latest Posts
Article information

Author: Corie Satterfield

Last Updated:

Views: 6334

Rating: 4.1 / 5 (42 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Corie Satterfield

Birthday: 1992-08-19

Address: 850 Benjamin Bridge, Dickinsonchester, CO 68572-0542

Phone: +26813599986666

Job: Sales Manager

Hobby: Table tennis, Soapmaking, Flower arranging, amateur radio, Rock climbing, scrapbook, Horseback riding

Introduction: My name is Corie Satterfield, I am a fancy, perfect, spotless, quaint, fantastic, funny, lucky person who loves writing and wants to share my knowledge and understanding with you.