API · Python

Python os.path.isfile() Method

The os.path.isfile() is an in-built python function used to check whether the specified path is a valid regular file or not.

On this page

Python os.path.isfile() method is one of the most common ways of checking the existence of a file and its validity. This method takes the path of a file as a parameter and checks whether the given path contains a valid file.

Syntax of the Python os.path.isfile() Method

os.path.isfile(path address)

Parameters

path address It is an address object of a file system path or a symlink. The object can either be an str or bytes.

Return

The return type of this method is a Boolean value. It returns the bool value true if the path address is of an existing regular file; otherwise, false is returned.

Example Codes: The os.path.isfile() Method

import os

directory = "/home/user/Desktop/fileName.txt"

file = os.path.isfile(directory)

print(file)

Output:

False

os.path.isfile() is an efficient method to ensure that a given path points to a file and that exists. This method helps us to avoid a FileNotFoundError at runtime.

Example Codes: Use Conditional Statement With the os.path.isfile() Method

import os

if os.path.isfile("/home/user/Desktop/fileName.txt"):
    print("File exist")
else:
    print("The file does not exist")

Output:

The file does not exist

Use this method to check whether the file exists or not before performing an action on the file. For example, copying, editing or deleting a file.

Example Codes: Enter Folder Path in the os.path.isfile() Method

import os

directory = "/home/user/Desktop"

file = os.path.isfile(directory)

print(file)

Output:

False

os.path.isfile() returns false when a folder path address is entered as a parameter. This method works for a valid file path only.

Example Codes: Set Path Address as Empty in the os.path.isfile() Method

import os

directory = ""

file = os.path.isfile(directory)

print(file)

Output:

False