2017-10-12 97 views
0

我需要將輸入與文本文件的第2行進行比較的代碼。我已經開始編寫代碼,但它不起作用,我現在在第三行是錯誤的,但不知道該怎麼做。將某行文本文件與輸入進行比較

Name = input("Enter name: ") 
with open("numbers") as MyFile: 
     if line 2 == Name: 
     print ("correct") 

回答

1

你可以使用readlines並獲得第二行:

Name = input("Enter name: ") 
with open("numbers") as MyFile: 
    line2 = MyFile.readlines()[1] 
    print(Name, line2) 
0

您需要定義 '2線'。試試:

name = input("Enter name: ") 
with open("numbers") as MyFile: 
    lines = MyFile.readlines() 
    if lines[1] == name: 
     print ("correct") 
1

我會盡量多提供一點解釋。你必須定義你的基本變量。人們可以看到第2行,根本就不是一個變量,因爲它有一個空間,並且從來沒有聲明過!

name = input("Enter name: ") 
with open("numbers") as f: 
    lines = f.readlines() # a list of all the lines 
    if lines[1] == name: # the second line (0 indexing) 
     print ("correct") 
相關問題