我需要将输入与文本文件的第2行进行比较的代码。我已经开始编写代码,但它不起作用,我现在在第3行是错的,但不知道该怎么做。
Name = input("Enter name: ")
with open("numbers") as MyFile:
if line 2 == Name:
print ("correct")
答案 0 :(得分:1)
您可以使用readlines
并获得第二行:
Name = input("Enter name: ")
with open("numbers") as MyFile:
line2 = MyFile.readlines()[1]
print(Name, line2)
答案 1 :(得分: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")
答案 2 :(得分:0)
您需要定义'第2行'。尝试:
name = input("Enter name: ")
with open("numbers") as MyFile:
lines = MyFile.readlines()
if lines[1] == name:
print ("correct")