2013-10-24 63 views
-5

我使用python3.3編寫了一個腳本,該腳本通過用戶輸入打開並讀取文件。讀取並打印用戶選擇的文件內容

txt_file = input("Text File: ") 

f = open(txt_file,"r") 
txt_include = f.read() 

print(txt_include) 

它告訴我,「txt_include沒有定義」

我無法找到一個辦法把TXT變量打開功能。我用很多函數來引用變量,但沒有任何工作。

什麼是我應該使用的正確語法?

+2

請提供您收到任何錯誤。你在用什麼版本的Python? 2.7或3+? –

+0

我在你的指導下編輯了我的帖子 – cankemik

回答

2

對於你正在嘗試做的,更好的方法是:

import os 

def print_file_contents(file_path): 
    assert os.path.exists(file_path), "File does not exist: {}".format(file_path) 
    with open(file_path) as f: 
     print (f.read()) 

user_input = raw_input("Enter a file path: ") # just input(...) in Python 3+ 
print_file_contents(user_input) 
0

F =開放(TXT,「R」)應該是f = open(txt_file,"r")

並使用raw_input代替input與輸入輸入數據將被解釋爲蟒變量,而不是字符串。

+0

抱歉。我在這裏寫錯了。在我的腳本中,它就像f = open(txt_file,「r」) – cankemik

+0

print語句隱含了'python 3',其中'input()'是正確的。 – cdarke

+0

打印語句也適用於python 2.7,其輸入行爲如我的答案中所述。 http://ideone.com/DVUSN4 – DhruvPathak

0

您的變量被稱爲txt_file,而不是txt。改變命名是一致的,它應該工作。

+0

對不起。我在這裏寫錯了。在我的腳本中它就像f = open(txt_file,「r」) – cankemik

0

您正在使用錯誤的變量名稱 - 它是txt_file,而不是txt

txt_file = input("Text File: ") 

f = open(txt_file, "r") 

編輯:好了,現在你的問題改變了代碼。那麼你會得到什麼錯誤信息?

+0

對不起。我在這裏寫錯了。在我的腳本中,它就像f = open(txt_file,「r」) – cankemik

+0

它告訴我f沒有被定義。 – cankemik

+0

@cankemik:請在將來再問一個問題時,將完整的錯誤信息完全顯示出來。並記住錯誤消息是你的朋友。 – cdarke

相關問題