gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:51:19 25 4
gpt4 key购买 nike

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

$ 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com