As you code appears to appears to be at the same indent level, each one of your if
/else
blocks will be executed one after another, therefore printing "Failed Attempt!" for each filepath that does not exist. Given your comment on March 12, you could use a for
loop followed by a if
/else
block to ensure that "Failed Attempt!" is printed only once all files had been checked for existance. See the code below (NOTE: As I don't have Windows 7 handy, I have not tested this, but it should work):
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!")
So to break it down step-by-step:
Import the
os
module, which you have obviously done this elsewhere already.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 asFalse
. 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.
- To store the filepath string of a file from
Next is the
for
loop. Each filepath string in theFILES
tuple will be made available to be checked by the indented code followingfor file in FILES:
. Thefile
variable is a string representing the current filepath fromFILES
, and it is local to the code associated with thefor
loop. The loop then checks if a file exists at the given filepath string infile
. If it the file exists,FILE_FOUND
is assigned the string stored infile
. Thebreak
statement then exits thefor
loop without any regard for any items inFILES
that haven't been checked. Otherwise, thefor
loop will continue to run until it runs out of items to check inFILES
.Finally, the
if
/else
code block will only run once thefor
loop has either found a file that exists, or has finished working through all items inFILES
. IfFILE_FOUND
evaluates asTrue
(by virtue of not beingNone
,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 inFILE_FOUND
by thefor
loop. If none of the filepath strings were found to exist in thefor
loop, theFILE_FOUND
variable will still beFalse
, therefore printing "Failed Attempt!".