所以我在系统中登录,他们可以输入他们喜欢的艺术家和流派。这将保存到文本文件中。但是知道我需要一个选项,他们可以改变自己喜欢的艺术家和流派。到目前为止这是代码。用户信息存储在同一行的文本文件中。
def registerUser():
usrFile_write = open(textfile, "a")
usrFile_write.write("\n" + username + ":" + password + ":" + date + ":" favArtist + ":" + favGenre + ":")
print("New Account Created!\n")
usrFile_write.close()
Menu()
def change():
menu=input("Change account preferences? (y/n")
if menu == "yes":
NewA=input("What is your new favorite artist...")
NewG=input("What is your new favorite genre...")
FavAG = open("user_DB.txt","w")
FavAG.write (NewA)
FavAG.write ("\n")
FavAG.write (NewG)
FavAG.close()
答案 0 :(得分:0)
首先,在处理文件时应始终使用with
语句。这方面的好处已有详细记载。所以这个:
usrFile_write = open(textfile, "a")
usrFile_write.write("\n" + username + ":" + password + ":" + date + ":" favArtist + ":" + favGenre + ":")
print("New Account Created!\n")
usrFile_write.close()
变为:
with open(textfile, "a") as usrFile:
usrFile.write("\n" + username + ":" + password + ":" + date + ":" favArtist + ":" + favGenre + ":")
print("New Account Created!\n")
现在,在纯文本文件中工作,您无法真正编辑特定行。要更新现有用户条目,您必须删除现有条目并在其位置创建新条目。这需要读取文件并重写整个内容,但特定行除外。您可以将其放入通用deleteUser
函数中,以便稍后重复使用:
def deleteUser(username):
with open(textfile, "r") as usrFile:
lines = usrFile.readlines()
with open(textfile, "w") as usrFile:
for line in lines:
if line.split(":")[0] != username:
usrFile.write(line)
然后,要修改用户,请删除其条目,然后使用新信息创建一个新条目。
现在这应该包括你了。我建议长期使用像sqlite这样的数据库,这项工作更适合它。