Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何修复使用txt文件登录和注册用户的python登录脚本_Python - Fatal编程技术网

如何修复使用txt文件登录和注册用户的python登录脚本

如何修复使用txt文件登录和注册用户的python登录脚本,python,Python,我编写了一个python脚本,用于登录和注册用户。它使用一个txt文件来存储用户名和密码。我是用英文写的。但是,它在常规python中不起作用。有人能告诉我需要改变什么来修复它吗? 编辑: 这是密码 file = open('accounts.txt', 'a+') lines = file.readlines() login = {} for line in lines: key, value = line.strip().split(', ') login[key] = value

我编写了一个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) 在读取以
a+
模式打开的文件之前,需要使用
.seek()

(2) 使用
.flush()
将强制立即将缓冲区中的任何数据写入文件

(3) 无需我对您的程序进行过多的重新构造,此编辑允许您立即访问新注册的用户进行登录。这是因为,由于该程序现在是结构化的,当您第一次打开accounts文件时,您只需将详细信息添加到
登录
字典中

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)

希望这有帮助

你能说得更具体些吗?哪个部分没有按预期工作?当我注册帐户时,它不会显示在文件中。另外,当我使用手动添加的有效帐户登录时,它只返回“No login”