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

标签 python

我写了一个 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/

相关文章:

用于 MySQL 查询执行的 python StringBuilder

使用私有(private)指数和模数以 64 位 block 形式解密 RSA 加密文件的 Python 代码

python - gtk.ScrolledWindow 具有 gtk.TextView 显示固定的第一行

python - Django接收数组ajax问题

python - 如何在 PyCharm 中拥有单独的输出窗口?

python - 从文本文件提取数据到 Pandas 时如何忽略垃圾数据?

python - flask 错误 : "Method Not Allowed The method is not allowed for the requested URL"

Python:使用 % 后清理 Windows 磁盘的脚本

python - 如何修复加载 MNIST 数据集时出现的 'No such file or directory' 错误

python - 提取 Panda Series 列表中的倒数第二个元素