Python os.path.isfile() Method

Python os.path.isfile() Method

  1. Syntax of the Python os.path.isfile() Method
  2. Example Codes: The os.path.isfile() Method
  3. Example Codes: Use Conditional Statement With the os.path.isfile() Method
  4. Example Codes: Enter Folder Path in the os.path.isfile() Method
  5. Example Codes: Set Path Address as Empty in the os.path.isfile() Method

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
Musfirah Waseem avatar Musfirah Waseem avatar

Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.

LinkedIn

Related Article - Python OS

  • Python os.set_handle_inheritable() Method
  • Python os.set_inheritable() Method
  • Python os.stat_result Class
  • Python os.renames() Method
  • Python os.get_handle_inheritable Method
  • Python os.get_inheritable Method