Python 如何检查路径是否是现有的常规文件而不是目录?
一个脚本用于在团队之间交换文件信息。它被用作:Python 如何检查路径是否是现有的常规文件而不是目录?,python,file,Python,File,一个脚本用于在团队之间交换文件信息。它被用作: $ 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 abso
$ 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/
该计划并没有像它应该的那样失败。在回顾中,我本应该看到这一切,但我没有
如何添加测试以确保路径是常规文件,该文件可能有扩展名,也可能没有扩展名(我不能简单地处理名称字符串)。。。那很容易。谢谢。嗯。。。那很容易。谢谢
os.path.exists(path) and not os.path.isdir(path)
import os.path
os.path.isfile(filename)