2011-08-25 127 views
0

我在寫一個小腳本,如果文件存在或不存在,它將打印。爲什麼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

你可能要考慮再看看'if' /'elif'語句。以「file」作爲變量名的 –

+2

不是一個好主意。如果你想在命名空間稍後打開一個文件,你會遇到問題。 – rocksportrocker

回答

2

你不應該用 「真」,但真比較。

此外,你在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 ...

+0

不要與布爾文字相比較!這就像在平常的演講中說「如果...是真的」,而不是「如果......」。 –

2

你寫了"True"而不是True。此外,您的ifelif陳述是相同的。

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

與'True'的比較是多餘的(只要使用'if file'),並且與'False'比較'not'(只要使用'if not file'或'else')。 – delnan

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) 
+0

+1使用pythonic這個詞。 –

相關問題