0

我正在为 Windows 7 创建一个 Python 3 程序,以搜索 CD 上安装可执行文件的常用名称并运行它。我尝试使用多个 os.path.exists 但是当它找到正确的文件时,它会打印出它找不到其他可能的文件名。请帮忙!

        if os.path.exists("D:/autorun.exe"):
            os.startfile("D:/autorun.exe")
        else:
            print("Failed Attempt!")
        if os.path.exists("D:/Install.exe"):
            os.startfile("D:/Install.exe")
        else:
            print("Failed Attempt!")
        if os.path.exists("D:/AutoRun.exe"):
            os.startfile("D:/AutoRun.exe")
        else:
            print("Failed Attempt!")
        if os.path.exists("D:/install.exe"):
            os.startfile("D:/install.exe")
        else:
            print("Failed Attempt!")
4

1 回答 1

0

由于您的代码似乎处于相同的缩进级别,因此您的每个if/else块将一个接一个地执行,因此打印“尝试失败!” 对于每个不存在的文件路径。鉴于您在 3 月 12 日的评论,您可以使用for循环后跟if/else块来确保“尝试失败!” 只有在检查了所有文件是否存在后才会打印。请参阅下面的代码(注意:由于我手边没有 Windows 7,因此我没有对此进行测试,但它应该可以工作):

import os
FILES = ('D:/autorun.exe', 'D:/Install.exe', 'D:/AutoRun.exe', 'D:/install.exe')
FILE_FOUND = False

for file in FILES:
    if os.path.exists(file):
        FILE_FOUND = file
        break

if FILE_FOUND:
    os.startfile(FILE_FOUND)
else:
    print("Failed Attempt!")

因此,逐步分解它:

  1. 导入os模块,你显然已经在别处做过了。

  2. The filepaths for each file to be checked are to be stored as a tuple in FILES. A tuple is used because it is 'immutable' and therefore we know it will be stored exactly as shown above. This is also handy as it will mean that the for loop will check each file in the order from left to right.

  3. FILE_FOUND is initially assigned as False. This will be used later for 2 things:

    • To store the filepath string of a file from FILES, if it exists.
    • To be use to determine if os.startfile() should be executed.
  4. Next is the for loop. Each filepath string in the FILES tuple will be made available to be checked by the indented code following for file in FILES:. The file variable is a string representing the current filepath from FILES, and it is local to the code associated with the for loop. The loop then checks if a file exists at the given filepath string in file. If it the file exists, FILE_FOUND is assigned the string stored in file. The break statement then exits the for loop without any regard for any items in FILES that haven't been checked. Otherwise, the for loop will continue to run until it runs out of items to check in FILES.

  5. Finally, the if/else code block will only run once the for loop has either found a file that exists, or has finished working through all items in FILES. If FILE_FOUND evaluates as True (by virtue of not being None, 0, False, or as per the python docs), os.startfile(FILE_FOUND) will be executed, where we know that the filepath string of the existing file had been previously stored in FILE_FOUND by the for loop. If none of the filepath strings were found to exist in the for loop, the FILE_FOUND variable will still be False, therefore printing "Failed Attempt!".

于 2014-04-19T16:01:33.837 回答