Escualo
Escualo

Reputation: 42082

How to check that a path is an existing regular file and not a directory?

One script is used to exchange file information amongst teams. It is used as:

$ share.py -p /path/to/file.txt

The argument checking ensures that /path/to/file.txt exists and has the correct permissions:

#[...]
# ensure that file exists and is readable
if not os.access(options.path, os.F_OK):
 raise MyError('the file does not exist')
# ensure that path is absolute
if not os.path.isabs(options.path):
 raise MyError('I need absolute path')
# ensure that file has read permissions for others
info = os.stat(options.path)
last_bit = oct(info.st_mode)[-1]
if not last_bit in ['4', '5', '6', '7']:
 raise MyError('others cannot read the file: change permission')

The problem is that one user sent:

$ share.py -p /path/to/

and the program did not fail as it should have. In retrospective I should have seen this coming, but I did not.

How can I add a test to ensure that path is a regular file which may or may not have an extension (I cannot simply process the name string)?

Upvotes: 1

Views: 532

Answers (2)

carl
carl

Reputation: 50554

import os.path
os.path.isfile(filename)

Upvotes: 9

Ned Batchelder
Ned Batchelder

Reputation: 375584

os.path.exists(path) and not os.path.isdir(path)

Upvotes: 4

Related Questions