os.path.exists() 用于路径中的文件? [英] os.path.exists() for files in your Path?

查看:51
本文介绍了os.path.exists() 用于路径中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常使用 os.path.exists() 来检查文件是否存在,然后再对其进行任何操作.

I commonly use os.path.exists() to check if a file is there before doing anything with it.

我遇到过这样一种情况,我正在调用位于配置的 env 路径中的可执行文件,因此可以在不指定 abspath 的情况下调用它.

I've run across a situation where I'm calling a executable that's in the configured env path, so it can be called without specifying the abspath.

有没有什么可以在调用之前检查文件是否存在的方法?(我可能会依赖 try/except,但首先我要寻找 os.path.exists() 的替代品)

Is there something that can be done to check if the file exists before calling it? (I may fall back on try/except, but first I'm looking for a replacement for os.path.exists())

顺便说一句 - 我在 Windows 上这样做.

btw - I'm doing this on windows.

推荐答案

您可以获取 PATH 环境变量,并尝试对路径中每个目录中的 .exe 执行exists()".但这可能会表现得很糟糕.

You could get the PATH environment variable, and try "exists()" for the .exe in each dir in the path. But that could perform horribly.

查找 notepad.exe 的示例:

example for finding notepad.exe:

import os
for p in os.environ["PATH"].split(os.pathsep):
    print os.path.exists(os.path.join(p, 'notepad.exe'))

更聪明的例子:

if not any([os.path.exists(os.path.join(p, executable) for p in os.environ["PATH"].split(os.pathsep)]):
    print "can't find %s" % executable

您有什么要避免异常的具体原因吗?(除了教条?)

Is there a specific reason you want to avoid exception? (besides dogma?)

这篇关于os.path.exists() 用于路径中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆