为什么Python说文件不存在?

2024-09-29 21:52:01 发布

您现在位置: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

Tags: 文件代码py脚本trueifosexists
3条回答

修正逻辑,让你的代码更“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)

你不应该和“真”比较,而应该和“真”比较。在

另外,你把if和elif中的“True”都比较一下。在

而不是

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

试试这个:

^{pr2}$

然后去掉elif。。。在

你在写"True"而不是True。另外,您的if和{}语句是相同的。在

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

相关问题 更多 >

    热门问题