2017-04-22 36 views
1

我写了一个python脚本来记录用户并注册。它使用一个txt文件来存储用户名和密码。我写在http://trinket.io。但是,它在普通的python中不起作用。任何人都可以告诉我需要改变以解决问题吗? 编辑: 这里是代码如何修复使用txt文件登录并注册用户的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') 
+1

请问您是否更具体?哪部分不按预期工作? – Windmill

+0

当我注册一个帐户时,它不会显示在文件中。另外,当我使用手动添加的有效帐户登录时,它仅返回“无登录” –

回答

1

下面编辑,由##### 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) 

希望这有助于!