Python program to check if a file exists

How to check if a file exists in Python:

This post will show you how to check if a file exists or not in Python. Often, we want to check if a file exists or not before trying to do any file operations. For example, before reading contents from a file or before writing anything to a file, we can check if it exists or not.

This post will show you two different ways to check if a file exists. Let’s take a look at these one by one.

Method 1: By using os.path.exists() method:

os.path.exists method is used to check if a path exists or not in Python. It takes one path as the parameter and returns one boolean value. It returns True if the path exists, else it returns False.

We can also use os.path.isfile(path) method. This method returns True if the given path is for an existing regular file.

For example:

from os.path import exists

file_path = 'sample.txt'

if exists(file_path):
    print("File exists")
else:
    print("File doesn't exists")

Similarly, we can use isfile as like below:

from os.path import isfile

file_path = 'sample.txt'

if isfile(file_path):
    print("Given path is a file")
else:
    print("Given path is not a file")

Method 2: By using pathlib module:

Starting from Python 3.4, we can also use pathlib module. This module can be used to create a Path object by providing the path of the file. Path class provides one method called is_file() which can be used to check if the given path is a file or not.

Below program shows how to do that:

from pathlib import Path

file_path = 'sample.txt'
f = Path(file_path)

if f.is_file():
    print("Given path is a file")
else:
    print("Given path is not a file")

is_file() method returns one boolean value and based on it, we can say the path is a file or not.

You might also like: