我正在编写一个代码,其中用户进行测验,所有这些信息都存储在CSV文件中。然后,在另一个程序中,我将用户输入一个用户名,如果匹配,它将为该用户打印分数等。但是,我让同一位用户再次进行测验,而不是打印所有用户所做的所有测验和分数,而只是打印最新的。
显示:我的CSV文件看起来像这样
ser15科学
Ser15 C科学
这些是行。我希望我的程序打印所有的测验和" Ser15"等级,但它只是打印最新的。如何使我的程序全部打印?这是我下面的代码...
def Report1():
found=False
UserFind=input("Please enter a username")
with open("Report.csv","r") as c:
for row in c:
details=row.split(",")
if UserFind in details[0]:
found=True
else:
pass
if found==True:
print(details[0])
print(details[1])
print(details[2])
print("These are your user's details!")
else:
print("User doesn't exist or wrong details...")
这是我的结果:
Please enter a choice: 3
Please enter a usernameSer15
Ser15
C
Sci-Med
These are your user's details!
您可以看到它打印他们的最新信息,而不是全部...
这是我项目的一部分,因此对任何帮助都非常感谢!
您的打印语句不是在循环中,而是在它之后。因此,他们只能跑一次。并且您检查found
以决定是否打印没有道理:基于是否匹配的任何行,而不是当前的打印。另外,无需进行else: pass
。您应该将代码更改为以下:
def Report1():
found=False
UserFind=input("Please enter a username")
with open("Report.csv","r") as c:
for row in c:
details=row.split(",")
if UserFind in details[0]:
print(details[0])
print(details[1])
print(details[2])
print("These are your user's details!")
found= True
if not found:
print("User doesn't exist or wrong details...")
问题简直就是
for row in c:
details=row.split(",")
if UserFind in details[0]:
found=True
不会停止循环,因此您将在最后一行中得到任何内容。
只需在found=True
之后添加break
即可在匹配行停止
请注意,如果您要执行多个搜索,则此线性搜索不是最佳的。最好用CSV行构建字典:
import csv
with open("Report.csv","r") as c:
cr=csv.reader(c)
database = {row[0]:row[1:] for row in c}
现在使用name in database
或/和database.get(name)
查询database
以获取其余信息。
当您通过CSV文件循环时,应检查是否找到并在循环中打印。
with open("Report.csv","r") as c:
for row in c:
details=row.split(",")
if UserFind in details[0]:
found=True
print(details[0])
print(details[1])
print(details[2])
print("These are your user's details!")
if not found:
print("User doesn't exist or wrong details...")
希望这会有所帮助。
def Report1():
found=False
UserFind=input("Please enter a username")
with open("Report.csv","r") as c:
for row in c:
details=row.split(",")
if UserFind in details[0]:
print(details[0])
print(details[1])
print(details[2])
print("These are your user's details!")
found= True
if not found:
print("User doesn't exist or wrong details...")
谢谢积累!