![](/img/trans.png)
[英]Why does Python say that a value does not exist when it specifically does?
[英]Why does Python say file does not exist?
我正在编写一个小脚本,如果文件存在或不存在,它将打印。
但是它总是说该文件不存在,即使该文件确实存在。
码:
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
您不应将“ True”与“ True”进行比较。
同样,您将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"
并删除精灵...
您正在写"True"
而不是True
。 另外,您的if
和elif
语句相同。
if not file:
print macinput+" command not found"
else:
print os.getcwd()
os.system("python "+macinput+".py")
print file
更正逻辑,并使您的代码更具“ 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.