登录系统在纯文本数据库中找不到用户名

login system not finding username on plain text database

这是我的代码:

name = input("What is your full name?")
age = input("How old are you?")
username = name[0:3] + age
password = input("What is your desired password?")
with open(name+'.txt', 'w') as details:
    details.write("Name: "+name)
    details.write("\nAge: "+age)
    details.write("\nUsername: "+username)
    details.write("\nPassword: "+password)
    print("Your details are saved in", name+'.txt')
details.close()
login = []
login = True
while login == True:
    login_name = input("What is your name?")
    login_age = input("How old are you?")
    username_attempt = input("Please enter your username:\n")
    password_attempt = input("Please enter your password:\n")
    username_finder = open(login_name+'.txt', 'r')
    for line in username_finder:
        if line == "\nUsername: "+login_name[0:3]+login_age:
            username = line
       #if line == 'Password: '+I DONT KNOW WHAT TO PUT HERE

        else:
            print("Sorry, this username does not exist")

现在从这些你可以看到我正在尝试从文本文件中获取用户名并将其与输入的 username 进行比较,但是当我 运行 它时,它说术语 username 未定义。

  • 最好在 with open.
  • 之前将用户名与文件扩展名连接起来
  • 使用with open时,不需要关闭文件描述符。
  • 简化用户交互(objective 条消息)。
  • 注意variable scope
  • 如果您愿意使用 DBMS
  • ,您的 ifs 可能会更简单(并且您的应用程序会更好)

#!/usr/bin/python3

name = input("Full Name: ")
age = input("Age: ")
username = name[0:3] + age   # VARIABLE SCOPE
password = input("Desired Password: ")
filename = name + ".txt"

with open(filename, 'w') as details:
    details.write("Name: "+name)
    details.write("\nAge: "+age)
    details.write("\nUsername: "+username)
    details.write("\nPassword: "+password)
    print("Details saved in: ", filename)

除此之外,您真的认为将用户及其凭据数据库保存在这种格式的纯文本文件中是个好主意吗?我相信您应该看看一些主题,例如 DBMS(MySQL、MongoDB、SQLite 等)。

MongoDB 是一个持久性 "key-value store" 数据库。

您可以获取数据为 JSON 格式、序列化、搜索特定键等:

{  
   "1":{  
      "Username":"Protoman",
      "Password":"dr.w1ll7"
   },
   "2":{  
      "Username":"Megaman",
      "Password":"d0g.Rus4"
   }
}

如果您不想依赖 process/daemon 的 DBMS 来管理,拥有纯文本数据库,您可以尝试 SQLite

这应该可以解决问题

for line in username_finder:
    if line.startswith('Username: '):
        if line.strip() == "Username: "+login_name[0:3]+login_age:
            username = line
            login = False
        else:
            print("Sorry, this username does not exist")

并且,请注意其他答案中提到的其他问题。

试试这个 sample.py

name = raw_input("Full name:: ")
age = raw_input("age:: ")
un = name[0:3]+age
passd = raw_input("pass:: ")
with open(name+'.txt','w') as details:
    details.write("name: {}".format(name))
    details.write("\nage: {}".format(age))
    details.write("\nusername: {}".format(un))
    details.write("\npassword: {}".format(passd))
print("Yours details are saved in file {}.txt".format(name))

fetch.py。我已经硬编码了文件路径。你可以循环阅读。

FILE_PATH = '/Users/kgowda/Desktop/my_work/play/agentX.txt'
USERNAME = ''
with open(FILE_PATH, 'r') as users:
    for line in users:
        if line.startswith("name"):
            USERNAME = line.split(":")[1]
if USERNAME is '':
    print("User not found")
else:
    print("User found")

运行 输出为

[mac] kgowda@blr-mp6xx:~/Desktop/my_work/play$ python sample.py 
Full name:: agentX 
age:: 30
pass:: hulkisstrong
Yours details are saved in file agentX.txt

[mac] kgowda@blr-mp6xx:~/Desktop/my_work/play$ cat agentX.txt 
name: agentX
age: 30
username: age30
password: hulkisstrong

[mac] kgowda@blr-mp6xx:~/Desktop/my_work/play$ python fetch.py 
User found

您的代码有很多错误,还有几个地方可以更清楚(或简洁)地完成。这是它的重做版本,我相信它可以满足您的需求:

import os

print("Register with login system.")
name = input("What is your full name? ")
age = input("How old are you? ")
password = input("What is your desired password? ")
username = name[0:3] + age
filename = username + ".txt"

with open(filename, "w") as details:
    details.write("Name: {}\n".format(name))
    details.write("Age: {}\n".format(age))
    details.write("Username: {}\n".format(username))
    details.write("Password: {}\n".format(password))

print("Your username is", username)
#print("Your details were saved in", filename)  # Don't need to show this.

login = []
login = True
print("\nPlease log in.")
while login == True:
    login_username = input("What is your username? ")
    filename = login_username + ".txt"
    if not os.path.isfile(filename):
        print("Sorry, that's not a valid username, try again.")
    else:
        login_password = input("What is your password? ")
        with open(filename, "r") as user_file:
            for line in user_file:
                line = line.strip()  # Removed newline at end.
                if line.startswith("Password:"):
                    password = line.split(" ")[1]
                    print("password read from file: ", repr(password))
                    break
        if password == login_password:
            login = False
        else:
            print("Sorry, that's the wrong password, starting over.")

print("You are now logged in.")