How to check if a file exists or not using Python?


You might wish to perform a specific action in a Python script only if a file or directory is present or not. For instance, you might wish to read from or write to a configuration file, or only create the file if it doesn't already exist

There are many different ways to check if a file exists and figure out what kind of file it is in Python.

Using OS Module

An inbuilt Python module called Os has tools for dealing with the operating system. We can access operating system features by using os. In Python, os.path is a sub-module of os. This is used to change the name of the common path.

Depending on whether a file is there or not, the os.path's two methods, isfile() and exists(), provide the values "True" or "False."

os.path.isfile() Method

This method etermines whether the specified path already contains a regular file or not.

Syntax

os.path.isfile(filepath)

Where, filepath represents the path of the file.

The return type is depending on whether a file is there or not, "True" or "False."

Example

Following is an example to check whether a file exists or not using os.path.isfile() method −

import os filepath= 'C:\Users\Lenovo\Downloads\Work TP\trial.py' doesFileExists = os.path.isfile(filepath) print (doesFileExists)

Output

Following is an output of the above code according to the existence of the file −

True

os.path.exists() Method

This method checks whether the given path exists or not.

Syntax

os.path.exists(filepath)

Where, filepath represents the path of the file.

The return type is depending on whether a file is there or not, "True" or "False."

Example

Following is an example to check whether a file exists or not using os.path.exists() method −

import os filepath= 'C:\Users\Lenovo\Downloads\Work TP\trial.py' doesFileExists = os.path.exists(filepath) print(doesFileExists)

Output

Following is an output of the above code according to the existence of the file −

True

Using pathlib Module

A built-in object-oriented interface for Python, called Pathlib, offers an object API for working with files and directories. The pathlib module offers two options for determining whether the file exists, similar to the os module.

Example - pathlib.path.exists() Method

Following is an example to check whether a file exists or not using pathlib.path.exists() method −

import pathlib filepath = pathlib.Path("C:\Users\Lenovo\Downloads\Work TP\trials.py") if filepath.exists(): print ("The given file exists") else: print ("The given file does not exists")

Output

Following is an output of the above code according to the existence of the file −

The given file does not exists

Example - pathlib.is_file() Method

Following is an example to check whether a file exists or not using pathlib.is_file() method −

import pathlib filepath = pathlib.Path("C:\Users\Lenovo\Downloads\Work TP\trial.py") if filepath.is_file(): print ("The given file exists") else: print ("The given file does not exists")

Output

Following is an output of the above code according to the existence of the file −

The given file exists

Using Glob Module

Using wildcard characters, the glob module is used to look for files whose filenames fit a specific pattern. This also provides "True" or "False" values to indicate whether the file is present.

Example

Following is an example to check whether a file exists or not using glob module −

import glob if glob.glob(r"C:\Users\Lenovo\Downloads\Work TP\trial.py"): print ("The given file exists") else: print("The given file does not exists")

Output

Following is an output of the above code according to the existence of the file −

The given file exists

Exception Handling Method

We have code written under "try" in the try and except statements, and the "except" statement checks the code for errors under "try." The "except" block is executed if any errors are found. As a result, we use the "try" statement to open the file and determine whether it exists or not. The IOError Exception that arises if the file is missing allows us to print the output and show that the file is missing.

Using "test -e," the first step is to confirm that the path to the file is valid. If the path is valid, we then use "test -f" or "test -d" to determine whether the file is present.

Example - 1

Following is an example to check whether a file exists or not using the exception handling method (IOError) −

try: file = open('C:\Users\Lenovo\Downloads\Work TP\trial.py') print("The given file exists") file.close() except IOError: print("The given file does not exists")

Output

Following is an output of the above code according to the existence of the file −

The given file exists

Example - 2

Following is an example to check whether a file exists or not using exception handling method(FileNotFoundError) −

try: file = open('C:\Users\Lenovo\Downloads\Work TP\trials.py') print("The given file exists") file.close() except FileNotFoundError: print("The given file does not exists")

Output

Following is an output of the above code according to the existence of the file.

The given file does not exists

Updated on: 18-Aug-2022

725 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements