由于您的代码似乎处于相同的缩进级别,因此您的每个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!")
因此,逐步分解它:
导入os
模块,你显然已经在别处做过了。
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.
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.
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
.
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!".