我写了一个 python 脚本来让人们登录并注册。它使用 txt 文件来存储用户名和密码。我写在 http://trinket.io 。但是,它在常规 python 中不起作用。谁能告诉我需要改变什么来修复它? 编辑: 这是代码
file = open('accounts.txt', 'a+')
lines = file.readlines()
login = {}
for line in lines:
key, value = line.strip().split(', ')
login[key] = value
while True:
command = input('$ ')
command_list = command.split(' ')
if command_list[0] == 'login':
username = command_list[1]
password = command_list[2]
try:
if login[username] == password:
print('login')
else:
print('no login')
except KeyError:
print('no login')
elif command_list[0] == "register":
file.write("\n")
file.write(command_list[1])
file.write(", ")
file.write(command_list[2])
elif command_list[0] == "help":
print("""To login, type login, then type the username and then type the password.
To register, type register, then type the username and then the password.""")
elif command_list[0]== "quit":
break
else:
print('unrecognised command')
最佳答案
以下编辑(标记为##### ADDED LINE
)应该可以解决您的问题。
说明:
(1) 在读取以 a+
模式打开的文件之前,您需要使用 .seek()
。
(2) 使用.flush()
将强制缓冲区中的所有数据立即写入文件。
(3) 无需我过多地重构您的程序,此编辑即可让您立即访问新注册的用户进行登录。这是因为,按照程序现在的结构,您只需在首次打开帐户文件时将详细信息添加到您的 login
字典中。
file = open('stack.txt', 'a+')
file.seek(1) ##### ADDED LINE (1)
lines = file.readlines()
login = {}
for line in lines:
key, value = line.strip().split(', ')
login[key] = value
...
elif command_list[0] == "register":
file.write("\n")
file.write(command_list[1])
file.write(", ")
file.write(command_list[2])
file.flush() ##### ADDED LINE (2)
login[command_list[1]] = command_list[2] ##### ADDED LINE (3)
希望这有帮助!
关于python - 如何使用txt文件修复python登录脚本来登录和注册用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43563076/