Python is a scripting language and is highly readable, interactive, high-level, and object-oriented. Python has fewer syntactic structures than other programming languages and uses English terms instead of punctuation.
Python’s key features are:
- Beginner-friendly - Python can be easily learned, maintained, implemented, and read by a novice. It is also interactive in nature.
- Object-Oriented language - Python encapsulates code within objects and supports the object-oriented programming style.
- Industry-oriented - Python as a programming language is extendable, portable, scalable, and cross-platform friendly. It has a standard library, supports GUI applications, and interactive mode.
While performing operations on files like writing or reading from a file, we need to first check if the file on which we are performing the particular operation exists or not.
We use the is_file() function, which is part of the Path class from the pathlib module, or exists() function, which is part of the os.path module, in order to check if a file exists or not in Python. We will go in-depth on these functions in the coming topics.
Want a Top Software Development Job? Start Here!
Full Stack Developer - MERN StackExplore Program
Explain Python exists()
The OS module in Python lets us interact with the operating system. This comes under Python’s standard utility modules and gives a portable way to use the dependent functions of the operating system. The exists() function in Python exists in the os.path module, which is a submodule of the python’s OS module and is used to check if a particular file exists or not.
Syntax
from os.path import exists
file_exists = exists(path_to_file)
Different Ways to Verify a File or Python Check if Directory Exists, Using Functions
There are multiple ways to check if a file or directory exists or not. In this current article, we are going to perform this check using Python functions. Some of them are explained briefly below-
How to Check if a File Exists in Python Using:
1. os.path.exists()
As mentioned in an earlier paragraph, we know that we use os.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.
Function Syntax
os.path.exists(path)
Parameter
Return type - Return a boolean type value, i.e., false if the path does not exist and true if it exists.
path - A string type or bytes type object referring to a system path.
Example
import os
# Specifying path
path = '/usr/local/bin/'
# Checking whether the specified path exists
isExisting = os.path.exists(path)
print(isExisting)
# Specifying path
path = '/home/User/Diksha/Desktop/file.txt'
# Checking whether the specified path exists
isExisting = os.path.exists(path)
print(isExisting)
Output
False
True
2. os.path.isfile()
os.path.isfile() is another method that is used to check if a particular regular file in Python exists or not.
Function Syntax
os.path.isfile(path)
Parameter
Return type - Return a boolean type value.
path - A string type or bytes type object referring to a system path.
Example
import os
# defining Path
path = 'C:/Users/simplilearn/Desktop/file.txt'
# Checking whether the specified path exists
isFile = os.path.isfile(path)
print(isFile)
# defining Path
path = '/home/User/Diksha/Desktop/'
# Checking whether the specified path exists
isFile = os.path.isfile(path)
print(isFile)
Output
True
False
Preparing Your Blockchain Career for 2024
Free Webinar | 5 Dec, Tuesday | 9 PM ISTRegister Now
3. os.path.isdir()
This function is used to check if a specified path exists in a directory or not. The specified path follows a symbolic path linking to the specified directory.
Function Syntax
os.path.isdir(path)
Parameter
Return type - Returns a boolean type value, i.e., false if the specified path to the existing does not exist, true if it does.
path - os.path.isdir(path)
Example 1
import os.path
# defining Path
path = '/home/User/Documents/file.txt'
# Check whether the specified path exists
isdir = os.path.isdir(path)
print(isdir)
# defining Path
path = '/home/User/Documents/'
# Check whether the specified path exists
isdir = os.path.isdir(path)
print(isdir)
Output
True
False
Example 2 - To Check if the Specified Path Is a Symbolic Path
import os.path
# Creating a directory
dirname = "Simplilearn"
os.mkdir(dirname)
# Creating a symbolic link to point to above directory
symbolink_path = "/home/User/Desktop/simp"
os.symlink(dirname, symbolink_path)
path = dirname
# Checking if
# specified path is an existing directory
isdir = os.path.isdir(path)
print(isdir)
path = symbolink_path
# Checking whether the specified path
# is an existing directory
isdir = os.path.isdir(path)
print(isdir)
Output
True
True
Learn 15+ In-Demand Tools and Skills!
Automation Testing Masters ProgramExplore Program
4. pathlibPath.exists()
The Python Pathlib module contains a number of classes that describe file system paths and have semantics that are acceptable for various operating systems. This module is part of Python's standard utility module collection. Concrete and Pure paths are the two types of path classes in the pathlib module. Pure routes only perform computations and do not perform I/O operations, whereas concrete pathways are inherited from pure paths and perform both I/O and computational activities.
The pathlib.Path.exists() method is mainly used to check if the given path points to an existing directory or a file.
Function Syntax
pathlib.Path.exists(path)
Parameter
Return type - Return a boolean type value, true if the path exists, false if it does not.
path - Object that represents the system path.
Example
from pathlib import Path
# defining Path
path = '/home/simplilearn/Desktop'
# Instantiating the Path class
obj = Path(path)
# Checking if the path points to and existing file
print(obj.exists())
Output
True
Choose The Right Software Development Program
This table compares various courses offered by Simplilearn, based on several key features and details. The table provides an overview of the courses' duration, skills you will learn, additional benefits, among other important factors, to help learners make an informed decision about which course best suits their needs.
Program Name Automation Testing Masters Program Full Stack Developer - MEAN Stack Caltech Coding Bootcamp Geo All All US University Simplilearn Simplilearn Caltech Course Duration 11 Months 11 Months 6 Months Coding Experience Required Basic Knowledge Basic Knowledge Basic Knowledge Skills You Will Learn Java, AWS, API Testing, TDD, etc. HTML, CSS, Express.js, API Testing, etc. Java, JavaScript, Angular, MongoDB, etc. Additional Benefits Structured Guidance
Learn From Experts
Hands-on TrainingBlended Learning Program
Learn 20+ Tools and Skills
Industry Aligned ProjectsCaltech Campus Connect
Career Services
17 CEU CreditsCost $$ $$ $$$$ Explore Program Explore Program Explore Program
Kickstart Your Career with Simplilearn
In this article, we discussed the various ways to check if a file or directory exists or not using Python. Before performing any operations on the files or directory using built-in Python functions, it is extremely crucial to check if a particular file or directory exists or not in Python.
To get deeper knowledge in file systems in Python, going through a thorough, comprehensive course of Python is a considerable choice. To make things easy and get on board to jumpstart your career as a Mobile and Software developer in Python, Simplilearn provides complete Python development training. Check it out to get started with your Python journey!
If you are looking to enhance your skills further, we would recommend you to check Simplilearn's Caltech Coding Bootcamp. This program can help you hone the right skills and make you job ready in no time.
If you have any questions, feel free to post them in the comments section below. Our team will get back to you at the earliest.