There can be file and directory with the same name. If you check using above methods, you can not identify whether it is a file or a directory.

Suppose you want to check if file “test-data” is present or not. In case if there is a directory with the name “test-data”, above functionos.path.exists() will return True. This is not expected as you are interested in the file (not the directory).

To avoid this teeter, you can use the following method.

Code for Checking only Files:

import os
os.path.isfile("test-data")

Above method will return False if there is no file “test-data”, even if the directory present with the same name.

Even if the file is present, you can find whether the file is accessible to write or to execute.

How to check if the File is Accessible to read, write or execute?

You can check the file if it is accessible for the various mode of accessing the file (ex. read, write or execute) using method os.access().

Syntax:

os.access(<path>, <mode>)

Along with the file path, you can provide accessible mode:

os.F_OK: to check existence of the file path

os.R_OK: to check if file is accessible to read

os.W_OK: to check if file is accessible to write

os.X_OK: to check if file is accessible to execute

This method returns True or False based on the existence of file path and permission to access the various accessible mode.

I am complete Python Nut, love Linux and vim as an editor. I hold Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack Portal.

Comments

Vernon Cole

July 31, 2017 at 5:51 pm

The second example would be more clear if it were explained that the file is actually processed in the “try” block — not just opened and closed to test for accessibility.
This is more “Pythonic” — that is clearer to read and more efficient to execute — than testing for accessibility, then later opening the file. It also eliminates a possible window of time, between testing for the existence of the file and opening it for use, when an outside agent could remove the file.

myfilename = 'my_file.txt'
try:
with open(myfilename) as myfile:
for line in myfile:
print(line.strip())
except IOError:
print('Trouble using file {}'.format(myfilename))<>/pre