Python如何修改txt文件中指定用户名对应的存储分数
实现指定用户分数更新功能
实现思路
因为TXT是纯文本文件,无法直接修改某一行的内容,所以采用「全量读取-匹配修改-全量覆写」的逻辑:
- 先读取Login.txt的所有行,存入列表做临时存储
- 遍历列表中的每一行,跳过空行后拆分用户名、密码、分数三个字段
- 匹配到目标用户名后,用新分数替换原有分数,重组该行内容
- 所有行处理完成后,把修改后的列表重新写入Login.txt覆盖原有内容
完整可运行代码
你可以直接把下面的update_user_score函数加到你现有代码里,我同时也修复了你原有SignUp函数可能产生多余空行的问题:
def SignUp(): print("Please enter a username and password.") newUsername = input("Your username: ") print("Cool now enter a password\n") newPassword = input("Your Password: ") print("Nice.") newscore = input("Now give me a score: ") # 判断文件是否为空,避免首行出现空行 import os file_exists = os.path.exists("Login.txt") is_empty = not file_exists or os.path.getsize("Login.txt") == 0 with open("Login.txt","a") as file: # 只有文件不是空的时候才先写换行 if not is_empty: file.write("\n") file.write(f"{newUsername},{newPassword},{newscore}") def Login(): userLogin = input("Please enter your username. ") userPass = input("Password: ") logged_in = False current_score = 0 with open('Login.txt', 'r') as file: for line in file: line = line.strip() # 跳过空行避免报错 if not line: continue username, password, score = line.split(',') if username == userLogin: logged_in = password == userPass current_score = score break if logged_in: print(f"Login success, your current score is: {current_score}") # 登录成功后可选择是否更新分数 update_choice = input("Do you want to update your score? (y/n): ").lower() if update_choice == 'y': new_score = input("Enter your new score: ") update_user_score(userLogin, new_score) else: print("Wrong username or password") def update_user_score(target_username, new_score): # 存储所有行的临时列表 all_lines = [] with open("Login.txt", "r") as file: for line in file: line = line.strip() if not line: continue username, password, old_score = line.split(',') if username == target_username: # 匹配到目标用户,替换分数 line = f"{username},{password},{new_score}" all_lines.append(line) # 全量覆写回文件 with open("Login.txt", "w") as file: file.write('\n'.join(all_lines)) print(f"Score updated successfully, new score is {new_score}") # 测试运行 SignUp() Login()
代码说明
update_user_score函数接收两个参数:要修改的用户名target_username和新分数new_score- 处理过程中会自动跳过文件中的空行,避免拆分字段时报错
- 修改完成后直接覆盖原文件,不会产生多余的临时文件
- 优化后的SignUp函数不会再产生多余的空行,避免后续读取时出现异常
内容的提问来源于stack exchange,提问作者Philip PoultonHaselier
相关产品推荐
相关产品推荐

