一个脚本用于在团队之间交换文件信息。它用作:
$ share.py -p /path/to/file.txt
参数检查确保 /path/to/file.txt
存在并具有正确的权限:
#[...]
# 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')
问题是一位用户发送了:
$ share.py -p/path/to/
程序并没有像它应该的那样失败。回想起来,我本应该预见到这一点,但我没有。
我如何添加测试以确保路径是一个常规文件可能有也可能没有扩展名(我不能简单地处理名称字符串)?
最佳答案
import os.path
os.path.isfile(filename)
关于python - 如何检查路径是现有的常规文件而不是目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3559617/