简体   繁体   English

为什么Python会说文件不存在?

[英]Why does Python say file does not exist?

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 == "True":
   print macinput+" command not found"
elif file == "True":
   print os.getcwd()
   os.system("python "+macinput+".py")
   print file

You should not compare with "True", but with True. 您不应将“ True”与“ True”进行比较。

Also, you compare both in the if and the elif with "True". 同样,您将if和elif中的“ 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... 并删除精灵...

You're writing "True" instead of True . 您正在写"True"而不是True Also, your if and elif statements are the same. 另外,您的ifelif语句相同。

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' 更正逻辑,并使您的代码更具“ 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM