我有一个代码,可以将用户名,密码和分数写入格式为:用户名,密码,分数的csv文件中。我有它,所以它在代码的开头写了用户名和密码:
def login_system():
loggedin = False
while not loggedin:
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login=open("login.csv")
reader = csv.reader(login)
username=input("What is your username: ")
password=input("What is your password: ")
for row in reader:
if row[0]==username and row[1]==password:
print("Welcome " + username)
loggedin=True
login=open("login.csv","a")
login.write(username + "," + password + "\n")
login.close()
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
我为用户1和用户2执行此操作。
print("User 1:")
login_system()
print("")
print("User 2:")
login_system()
在代码中,这会将用户名和密码放入第0列和第1列。
然后在游戏结束时,将比分写入csv文件。然后,我要努力的部分是将分数写入第2列。我需要将其写在第2行的csv文件中的下一个可用单元格上。
对此将提供任何帮助。
迪伦
答案 0 :(得分:0)
如果我正确解释了您的请求,则只需修改以下行:
login.write(username + "," + password + "\n")
与
login.write(username + "," + password + ",")
,然后将分数与行终止符“ \ n”相加。 这样,您将获得:
username,password,score
全部在同一行。
答案 1 :(得分:0)
我重写了您的代码,因此可读性强:
def login_system():
loggedin = False
with open("login.csv", newline='') as fid:
reader = csv.reader(fid, delimiter=",")
login = list(reader)
while not loggedin:
ans=input("Do you have an account? (yes/no) ")
if ans.lower()=="yes":
username=input("What is your username: ")
password=input("What is your password: ")
if [username, password] in login:
print("Welcome " + username)
loggedin=True
return loggedin
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
elif ans.lower() == "no":
username=input("New username: ")
password=input("New password: ")
with open("login.csv", "a") as login:
login.write(username+","+password+"\n")
print("Welcome "+username)
loggedin = True
return loggedin
with
语句进行文件处理最后一个您的实际问题:
写入新文件或覆盖旧文件会更容易。而且速度更快。