用户名和密码 Python 程序使用字典并写入文件,我该怎么做而不重复



首先,我是python的初学者,所以除非必要,否则请不要回答任何高级答案。我正在编写一个需要用户名和密码的登录程序,我正在尝试这样做,以便它读取一个文件,然后将其添加到字典中,然后人们登录或创建新的登录名并将新的登录名(如果有的话(写入文件,以便在我重新运行程序时读取并写回字典中......我遇到的问题是,当创建新登录名时,它会将新登录名写入文件,但同时它会再次将字典中的另一个登录名写入文件。有没有办法确保用户名和通行证不会重复?下面是文本文件的外观示例:

joe  dw < ---- old login and pass
joe  dw <---- repeated login and pass
jack  dw <--- new login and pass

这是我的代码,如果它看起来令人困惑,或者如果你生气我没有很多评论,我只是评论我所做的一切的新手:

login = {} 
def fileToDict():
'''this reads the file and writes it into the dictionary'''
with open("login.txt", "r") as f:
for line in f:
(key, val) = line.split()
login[key] = val
def addUser(username, password):
'''basic user and login function'''
if username in login:
print("Username already exists")
else:
login[username] = password
dictToFile()
def checkUser(username, password):
'''checks where the username and password is in the dictionary'''
if username in login:
if password == login[username]:
return True
else:
return False
else:
return False
def dictToFile():
'''this writes the current dictionary into a file'''
with open("login.txt", "a+") as f:
for k, v in login.items():
line = '{}  {}'.format(k, v) 
print(line, file=f)        
fileToDict()
addUser("john","dw")
print(login)

dictToFile中,您打开了要追加的文件 ("a+"(,这将添加到文件的末尾。 如果要覆盖已有的内容,请使用"w"

相关内容

最新更新