【问题标题】:Why does Python say file does not exist?为什么Python说文件不存在?
【发布时间】:2011-08-25 08:02:41
【问题描述】:

我正在编写一个小脚本,它会打印文件是否存在。

但它总是说文件不存在,即使文件确实存在。

代码:

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

【问题讨论】:

  • 您可能想再看看if/elif 语句。
  • 将“文件”作为变量名并不是一个好主意。如果你想稍后在命名空间中打开一个文件,你会遇到问题。

标签: python windows-xp operating-system system


【解决方案1】:

你写的是"True"而不是True。此外,您的ifelif 语句是相同的。

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

【讨论】:

  • True比较是多余的(只用if file),和False比较是not(只用if not fileelse)。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    此外,您将 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...

    【讨论】:

    • 不要与布尔文字比较!这就像说“如果它是真的……”而不是普通话中的“如果……”。
    猜你喜欢
    • 1970-01-01
    • 2021-06-05
    • 2022-11-22
    • 2022-11-15
    • 1970-01-01
    • 2021-12-20
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多