繁体   English   中英

如何检查路径是现有的常规文件而不是目录?

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

一个脚本用于在团队之间交换文件信息。 它用作:

$ 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 /路径/到/

并且程序没有失败,应该有的失败。 回顾过去,我应该看到这种情况的到来,但我没有。

如何添加测试以确保路径是带有或不带有扩展名的常规文件(我不能简单地处理name字符串 )?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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