AppDividend
Latest Code Tutorials

Python os.path.isfile() Function with Example

0

Python provides an inbuilt OS module that can be used for interacting with the operating system. The os.path module is a submodule of the OS module used for common path name manipulation.

Python os.path.isfile()

The os.path.isfile() is an inbuilt Python function that returns True if the path is an absolute pathname. On Unix, that means it begins with a slash; on Windows, it begins with a (back)slash after chopping off a potential drive letter.

Syntax

os.path.isfile(path)

Parameters

The os.path.isfile() function takes a path as a parameter representing an object representing a file system path. A path-like object is either a string or bytes object representing a path.

Return Value

The os.path.isfile() method returns a Boolean value of class bool. The os.path.isfile() method returns True if the specified path is an existing regular file. Otherwise, it returns False.

Example

Let’s define a folder path and pass that path to the isfile() function.

import os

path = "/Users/krunal/Desktop/code/pyt/database"

isFile = os.path.isfile(path)

print(isFile)

Output

False

You can see that we have passed the folder path and not the file path to the isfile() function, and hence it returns False. Let’s pass the file path and see the output.

import os

path = "/Users/krunal/Desktop/code/pyt/database/app.py"

isFile = os.path.isfile(path)

print(isFile)

Output

True

To check if the file exists in the file system using Python, use the os.path.isfile() function. If you attempt to navigate or open a non-existent file, then this would cause an error. 

There are three different Python functions that can be used to verify the existence of a file:

  1. path.exists()
  2. path.isfile()
  3. exists()

That is it for os.path.isfile() function.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.