2016-04-29 96 views
-2

我試圖根據用戶輸入的輸入打開一個文件。用變量打開一個文件

這是我現在的代碼,但它似乎總是直接轉到except塊,即使在輸入正確的文件名時也是如此。

filename = input("Enter a filename: ") 

try: 
    open(filename.txt, "w") 
    print("Succesfully opened", filename,".txt") 

except: 
    print("File cannot be found.") 

任何幫助,將不勝感激!

+7

提示:取出try/except,以便您可以看到實際獲得的錯誤。 – JETM

回答

4

這將工作。

filename = input("Enter a filename: ") 

try: 
    # Access filename as a variable 
    open(filename + ".txt", "w") 
    print("Succesfully opened", filename,".txt") 

# Catch the specific exception 
except IOError: 
    print("File cannot be found.") 
2

變化open(filename.txt, "w")open(filename + '.txt', "w")

-1

正如標誌着@Bharel,這將工作:

filename = input("Enter a filename: ") 

try: 
    open(filename + ".txt", "w") 
    print("Succesfully opened", filename,".txt") 

except: 
    print("File cannot be found.") 

的問題是在open(filename.txt, "w"),因爲.TXT是不是字符串,那麼最簡單的方法是連接與文件名延期。