Python os.path.exists() Method

Python os.path.exists() Method

  1. Syntax of the Python os.path.exists() Method
  2. Example Codes: The os.path.exists() Method
  3. Example Codes: Use a symlink in the os.path.exists() Method
  4. Example Codes: Use the os.path.exists() Method to Check for a Valid Directory

Python os.path.exists() method determines a valid path or symbolic link.

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

os.path.exists(path address)

Parameters

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

Return

The return type of this method is a Boolean value, and it returns the bool value true if the path/directory/link exists. Otherwise, a bool value false is returned when the file doesn’t exist or a link is broken.

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

import os

pathAddress = '/usr/local/bin/'

Exists = os.path.exists(pathAddress)

print(Exists)

Output:

True

The method os.path.exists() returns false when access is denied to obtain the information on the required file, even though the file might physically exist.

import os

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

Exists = os.path.exists(directory)

print(Exists)

Output:

False

os.path.exists() is a portable and effective way to use the operating system-specific functionality. This method can also return true if the given path refers to an open file descriptor; otherwise, it returns false.

Example Codes: Use the os.path.exists() Method to Check for a Valid Directory

import os

flag = os.path.exists('E:/demos/files_demos/account/')

if flag:
    print('The path exists')
else:
    print('The path does not exist')

Output:

The path does not exist

os.path.exists() helps us not only to check the existence of a certain file but also the existence of a valid file directory. Alternatively, use the is_dir method to check for a directory existence.

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