os.path.exists() for files in your Path?

前端 未结 5 2043

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

I\'ve run across a situation where I\'m calling a executable that

5条回答
  •  鱼传尺愫
    2021-02-04 07:55

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

    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'))
    

    more clever example:

    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?)

提交回复
热议问题