Почему Python говорит, что файл не существует? - PullRequest
0 голосов
/ 25 августа 2011

Я пишу небольшой скрипт, который будет печатать, если файл существует или нет.

Но он всегда говорит, что файл не существует, даже если файл действительно существует.

Код:

file = exists(macinput+".py")
print file
if file == "True":
   print macinput+" command not found"
elif file == "True":
   print os.getcwd()
   os.system("python "+macinput+".py")
   print file

Ответы [ 3 ]

2 голосов
/ 25 августа 2011

Вы пишете "True" вместо True. Кроме того, ваши операторы if и elif совпадают.

if not file:
   print macinput+" command not found"
else:
   print os.getcwd()
   os.system("python "+macinput+".py")
   print file
2 голосов
/ 25 августа 2011

Исправляя логику и делая ваш код немного более "питоническим"

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)
2 голосов
/ 25 августа 2011

Не следует сравнивать с «Истиной», но с Истиной.

Кроме того, вы сравниваете как в if, так и в elif с "True".

вместо

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

попробуйте это:

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

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

и удали элиф ...

...