在Python中将用户输入与文件记录匹配
我正在制作一个程序,要求用户输入他们的学生ID,并显示学生ID和学生姓名等学生信息。我首先要求用户输入他们的id,然后它将读取一个.txt文件并检查学生id是否匹配,然后它将打印出用户正在查找的特定学生的.txt文件信息的内容 这是我的文件内容在Python中将用户输入与文件记录匹配,python,Python,我正在制作一个程序,要求用户输入他们的学生ID,并显示学生ID和学生姓名等学生信息。我首先要求用户输入他们的id,然后它将读取一个.txt文件并检查学生id是否匹配,然后它将打印出用户正在查找的特定学生的.txt文件信息的内容 这是我的文件内容 201707001 Michael_Tan 201707002 Richard_Lee_Wai_Yong 201707003 Jean_Yip 201707004 Mark_Lee 201707005 Linda_Wong 201707006
201707001 Michael_Tan
201707002 Richard_Lee_Wai_Yong
201707003 Jean_Yip
201707004 Mark_Lee
201707005 Linda_Wong
201707006 Karen_Tan
201707007 James_Bond
201707008 Sandra_Smith
201707009 Paul_Garcia
201707010 Donald_Lim
这是我的源代码
# user can find out the student info
userInput = input("Please enter a student ID: ")
# read the students file
with open('C:\\Users\\jaspe\\Desktop\\PADS Assignment\\Student.txt') as f:
studentFile = f.readlines()
for student in studentFile:
stdId, stdName = student.strip().split(" ",1)
# check if the student exist
matched = True
while matched:
if userInput == stdId:
print("True")
else:
print("False")
matched = False
break
但是我得到的输出是假的,即使我输入了准确的studentID,你应该在阅读文件时进行检查。否则,您将拆分并获取信息,但这些数据将在后续迭代中丢失。试试这个:
with open('C:\\Users\\jaspe\\Desktop\\PADS Assignment\\Student.txt') as f:
studentFile = f.readlines()
for student in studentFile:
stdId, stdName = student.strip().split()
if userInput == stdId:
print(stdName)
break
更好的是,对于大型文件,逐行迭代。不要使用
f.readlines
,因为它会将所有数据加载到内存中
with open('C:\\Users\\jaspe\\Desktop\\PADS Assignment\\Student.txt') as f:
for line in f:
stdId, stdName = line.strip().split()
if userInput == stdId:
print(stdName)
break
正如它所示,您的代码在每个ID和名称之间循环,并将每个ID和名称分配到
stdId
和stdName
,但在检查匹配项之前,该循环将退出。。。因此,它只保存循环中存储在这些变量中的最后一个值。你需要在循环中进行检查,也是这样
# user can find out the student info
userInput = input("Please enter a student ID: ")
# read the students file
with open('C:\\Users\\jaspe\\Desktop\\PADS Assignment\\Student.txt') as f:
studentFile = f.readlines()
for student in studentFile:
stdId, stdName = student.strip().split(" ",1)
# check for a match here, break the loop if a match is found
使用
raw\u input
代替input
您几乎不想使用输入
,因为它进行评估。在这种情况下,键入一个精确的整数将为您提供一个整数,而文件将为您提供一个字符串,因此它将不匹配
代码中还有其他次要/主要问题
- 如果使用
输入循环,则将永远循环打印userInput==stdId
True
- 你从来没有真正搜索过学生ID,你只是检查了上一个循环中的最后一个设置
- (对于这一点,如果您计划执行多个用户查询,或者只是在阅读文件行时查看一个简单脚本,我建议您使用字典)
C:\\Users\\jaspe\\Desktop\\PADS assignment\\Student.txt