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

标签 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 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/

相关文章:

python - 如何捕获Python中的任何套接字错误?

python - 使用嵌套字典填充缺失值

file - 创建 2 个文件并向它们写入与 Lisp 中另一个文件不同的内容

python - 将文件转换为字符串,然后重建该字符串并再次使其成为文件

javascript - 文件下载后重新加载页面

python - 如果它们高于特定阈值,则将 numpy 数组元素设置为零

python - Python中的R函数rep()(复制列表/向量的元素)

python - 用于匹配括号之间数据但具有内部匹配模式的正则表达式

c - 如何从C中的文件中获取未知数量的字符串?

c - 抓取windows文件信息