为什么Python说文件不存在?
我正在写一个小脚本,用来检查一个文件是否存在。
但是它总是说文件不存在,尽管这个文件实际上是存在的。
代码:
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
你写的是 "True"
,而不是 True
。另外,你的 if
和 elif
语句是一样的。
if not file:
print macinput+" command not found"
else:
print os.getcwd()
os.system("python "+macinput+".py")
print file
2
你不应该用 "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"
并且去掉 elif...
2
纠正逻辑,让你的代码更符合“Python风格”
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)