2017-04-22 40 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) 

希望這有助於!