2015-08-15 133 views
-1

我是一個Python新手,我想,我想知道是否有一種方法來讀取文件,然後檢查用戶的輸入是否等於該文件的文本。如何檢查文件是否等於python中的變量?

我一直在試圖創建一個密碼程序,而不必在程序中顯示密碼/變量。如果還有其他方法可以做到這一點,而不是做.read()和事情(如果他們不工作),那麼我會很樂意聽到這些建議!

+1

這是一個很廣泛的問題,有關安全,你要明文存儲密碼是什麼? –

+0

你不能讀取沒有'.read()'的文件 - 它 - 所以我不確定你在問什麼。請編輯問題並添加沒有工作的代碼(正如您所說的,_without不做'.read()'_,所以我假設使用'.read()'寫了一些不起作用的東西)。 –

+0

OP表示如果'.read()'不起作用。 – Cyphase

回答

0

這應做到:

# The path to the file 
filepath = 'thefile.txt' 

# This is how you should open files 
with open(filepath, 'r') as f: 
    # Get the entire contents of the file 
    file_contents = f.read() 

    # Remove any whitespace at the end, e.g. a newline 
    file_contents = file_contents.strip() 

# Get the user's input 
user_input = input('Enter input: ') 

if user_input == file_contents: 
    print('Match!') 
else: 
    print('No match.') 
+0

*如果還有另外一種方法可以不做.read()* –

+0

@PadraicCunningham,如果還有另外一種方法可以不做.read()和things_ **(如果它們不起作用)** _then我會很高興聽到這些建議!_ – Cyphase

+0

*無需在程序中顯示密碼/變量。* –

相關問題