Python – How to Check if a file or directory exists
Last Updated : 24 Apr, 2024
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:
- os.path.exists(path): Checks if a file or directory exists at the given path.
- os.path.isfile(path): Checks if a file exists at the given path.
- os.path.isdir(path): Checks if a directory exists at the given path.
- 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.
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