开发者

Why does Python say file does not exist?

开发者 https://www.devze.com 2023-03-30 20:50 出处:网络
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.

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

精彩评论

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

关注公众号