8 Ways to Check if a File Exists Using Python

Python’s dependency on exterior information is an important facet, it is sensible to pay heed to the bottom/supply information earlier than executing any code. Earlier than working a specific program, that you must guarantee your supply information exist on the specified location.

Each developer understands the necessity to create fall again codes, which might save a prorgram from failing within the case {that a} situation is not met. In Python, there are a number of methods to verify if a file exists; listed here are the highest strategies you must find out about.

1. Try to Besides Statements

The try and except statement checks a command and produces an output. Within the code beneath, the attempt assertion will try to open a file (testfile.txt). If Python’s processor is ready to find the file, it can open the file and print the outcome File is open and out there to be used.

f = open('testfile.txt')
print("File is on the market to be used")
besides IOError:
print('File will not be accessible')

Using try and except method in Python

If it encounters an error, it can print the outcome File will not be accessible. As soon as the total code is compiled and executed, it can shut the open file if it was opened.

Python’s dependency on exterior information is an important facet, and that you must pay heed to the bottom/supply information, earlier than executing any codes.

Earlier than executing a specific program, guarantee your supply information exist on the particular location.

2. Os.path.isfile(path)

Python has a built-in module OS which may be referred to as upon to work together with the underlying information, folders and directories. Python’s os.path.isfile() methodology can be utilized to verify a listing and if a selected file exists.

Step one is to import the built-in operate utilizing the import os.path library. The following command checks if the file exists on the particular location.

import os.path
os.path.isfile(r"C:UsersWini BhallaDesktopPython check file.txt")

Using os.path.isfile(path) in Python to check a file's status

The output returns True, because the file exists on the particular location. If the file doesn’t exist, Python will return False.

3. Os.path.exists(path)

On comparable grounds, the import os library assertion can be utilized to verify if the listing exists in your system.

The syntax is slightly easy:

Import os.path
os.path.exists(r"C:UsersWini BhallaDesktoptest")

Using os.path.exists(path) to check a file's status

Identical to the earlier step, if the listing/folder is discovered on the required system path, Python returns True, and subsequently, False, if the listing/folder isn’t discovered.

Associated: Learning Python? Here’s How to Copy a File

4. Os.Path.Isdir(path)

Identical to os.path.isfile and os.path.exists(), os.path.isdir() is a sub-function of the os library. The one distinction right here is that this command solely works for directories. As anticipated, using this syntax returns a boolean worth primarily based on the existence of directories.

For instance:

import os
os.path.isdir(r"C:UsersWini BhallaDesktopOS")

The output is True, for the reason that folder/listing exists on the specified path.

import os
os.path.isdir(r"C:UsersWini BhallaDesktoptestdirectory")

Check existing file status using os.path.lisdir(path)

The output is False, for the reason that folder/listing doesn’t exist on the specified path.

5. Pathlib.path.exists()

Python 3.4 and above variations provide the Pathlib module, which may be imported utilizing the import operate. Pathlib captures the required functionalities in a single place, and makes it out there by way of numerous strategies to make use of with the trail object.

To Use Pathlib:

import pathlib
file = pathlib.Path(r"C:UsersWini BhallaDesktopPython check file.txt")
if file.exists ():
print ("File exists")
print ("File doesn't exist")


As per the existence of the file, the output will show whether or not or not the file exists within the specified path. Ideally, the code within the print assertion may be modified, as per the necessities of your program

6. Os.listdir(path)

The listdir methodology in Python returns an inventory of the all information in a selected listing, as specified by the person. Nevertheless, this methodology won’t return any information present in subfolders.

The listdir methodology solely accepts one parameter, the file path. Ideally, the file path shall be file and folder names you’d wish to retrieve.

The essential syntax contains:


Within the instance beneath, you possibly can create a loop to undergo all of the information listed within the listing after which verify for the existence of the required file declared with the if assertion.

import os
path = r'C:UsersWini BhallaDesktop'
information = os.listdir(path)
print (information)

This code will print out the checklist of information out there within the present listing.

import os
path = r'C:UsersWini BhallaDesktop' information = os.listdir(path)
for f in information:
if f == "check.txt":
print("File exists")
print("File doesn't exist")


Additional on, when the loop is run, the listdir operate together with the if assertion logic will cycle by way of the checklist of information and print out the outcomes, relying on the circumstances handed inside the print assertion.

Associated: Use Loops With Lists in Python

7. Glob Module

The glob module matches all of the pathnames with the required parameters and succinctly permits you to entry the file system. Since glob is used for sample matching, you should utilize it to verify a file’s standing.

There are two references of the trail:

If the file is discovered, the code will return True, in any other case it’s going to return False.

An instance of Glob’s utilization:

import glob
if glob.glob(r"C:UsersWini BhallaDesktoptest.txt"):
print ("File exist")
print("File doesn't exist")

Glob module Python

The output from this code will print the outcome, if the file is discovered.

8. Sub-process

The check command within the sub-process module is an environment friendly approach of testing the existence of information and directories. The check instructions solely work in Unix primarily based machines and never Home windows primarily based OS machines.

You should utilize the next instructions as per your wants:

  • check -e: Examine the existence of a path
  • check -f: Examine the existence of a file
  • test-d: Examine the existence of a folder

Verifying a Path With Sub-process:

from subprocess import run
run(['test', '-e', 'testfile.txt']).returncode == 0
run(['test', '-e', 'im-not-here.txt']).returncode == 0

This code referred to as the check operate adopted by ‘-e’ to confirm the existence of a path. The operate reveals False for an invalid path.

Verifying a File With Subprocess:

run(['test', '-f', 'testfile.txt']).returncode == 0
run(['test', '-f', 'testdirectory']).returncode == 0

The ‘-f’ operate assessments the existence of a file and returns False for a listing.

Verifying a Listing With Subprocess:

run(['test', '-d', 'testfile.txt']).returncode == 0
run(['test', '-d', 'testdirectory']).returncode == 0

The ‘-d’ operate assessments the existence of a listing and returns False for any file question within the check command.

Which Command Will You Use to Find Your Information?

Python is a comparatively easy-to-use language, and it affords lots of choices to the top customers. For checking the existence of a file(s), you should utilize any of the procedures listed above.

Nevertheless, for those who’re a newbie, there are all the time methods to study Python. Since Python is an unlimited language, it is best to spend a while understanding the completely different nuances and its vary of instructions.

red blue neon python
What Does Python Do and What Can It Be Used For?

Python is extremely versatile, with applications ranging from web development to data analysis.

Read Next

About The Creator

https://www.makeuseof.com/check-if-a-file-exists-using-python/ | 8 Methods to Examine if a File Exists Utilizing Python


Inter Reviewed is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – admin@interreviewed.com. The content will be deleted within 24 hours.

Related Articles

Back to top button