简体   繁体   中英

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 )?

import os.path
os.path.isfile(filename)
os.path.exists(path) and not os.path.isdir(path)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM