2013-03-04 92 views
-1

所以我有這個代碼,我試圖讓它打開一個文件。但是,代碼的異常部分總是被執行。Python文件未打開文件?

def main(): 
    #Opens up the file 
    try: 
     fin = open("blah.txt") 
     independence = fin.readlines() 
     fin.close() 
     independence.strip("'!,.?-") #Gets rid of the punctuation 
     print independence 
     #Should the file not exist 
    except: 
     print 'No, no, file no here' 

if __name__ == "__main__": 
    main() 

我檢查,看看是否該文件名拼寫正確,它是,並且該文件在同一目錄作爲Python文件,我以前用過這個代碼。爲什麼它不起作用?

+3

請修復縮進! – 2013-03-04 15:48:15

+4

你可以打印異常並找出原因! :) – 2013-03-04 15:49:03

+0

就像Fredrik說的那樣,我們不能確切地知道你的Python程序正在執行什麼,因爲縮進有點不合常理 - 你能修正它,看起來就像你在編輯器/ IDE中一樣嗎? – bouteillebleu 2013-03-04 15:51:00

回答

6

independence是一個字符串列表。您不能在列表中調用strip。 試試這個:

def main(): 
    fin = open('blah.txt', 'r') 
    lines = fin.readlines() 
    fin.close() 
    for line in lines: 
     print line.strip("'!,.?-") 

if __name__ == '__main__': 
    try: 
     main() 
    except Exception, e: 
     print '>> Fatal error: %s' % e 
+0

;當你在它的時候,使用'打開(「blah.txt」)作爲fd'而不是 – 2013-03-04 15:54:11

+0

這樣做。謝謝! – user1768884 2013-03-04 15:55:07

+0

非常歡迎。 – 2013-03-04 15:55:18