开发者

Why does Python say file does not exist?

I am writing a small script which will print if a file exists or not.

But it always says that the file does not exist, even though the file actually exists.

Code:

file = exists(macinput+".py")
print file
if file == "Tr开发者_Go百科ue":
   print macinput+" command not found"
elif file == "True":
   print os.getcwd()
   os.system("python "+macinput+".py")
   print file


You're writing "True" instead of True. Also, your if and elif statements are the same.

if not file:
   print macinput+" command not found"
else:
   print os.getcwd()
   os.system("python "+macinput+".py")
   print file


Correcting logic, and making your code a little more 'pythonic'

import os
filename = macinput + ".py"
file_exists = os.path.isfile(filename)
print file_exists
if file_exists:
   print os.getcwd()
   os.system("python {0}".format(filename))
   print file_exists
else:
   print '{0} not found'.format(filename)


You should not compare with "True", but with True.

Also, you compare both in the if and the elif with "True".

instead of

if file == "True":
    print macinput + " command not found"

try this:

file = exists(macinput+".py")
print "file truth value: ", file

if file:
    print macinput + " command found"
else:
    print macinput + " command NOT found"

and remove the elif...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜