简体   繁体   English

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

[英]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: 参数检查可确保/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')

The problem is that one user sent: 问题是一位用户发送了:

$ share.py -p /path/to/ $ share.py -p /路径/到/

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 )? 如何添加测试以确保路径是带有或不带有扩展名的常规文件(我不能简单地处理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