按用户名查找密码

时间:2015-09-25 10:06:11

标签: python csv

我已经有了这段代码。现在我想更改代码,当有人输入用户名时,他必须填写属于用户名的正确密码。

import csv
        csvbestand='inlog.csv'
        csv = open('inlog.csv', 'r').read().split('\n')[1].split(';')
        username= input("Fill in your username: ")
        if username == "admin" or username in csv:
            print("Username found")
            break
        else:
            print("Username not found")

    while True:
        import csv
        csvbestand='inlog.csv'
        csv = open('inlog.csv', 'r').read().split('\n')[2].split(';')
        password = input("Fill in your password: ")
        if password == "admin" or password in csv:
            print("Congratiulations")
            break
        else:
            print("Password not right")

因此,当用户名是“John”时,我只想要属于“John”的密码作为正确的密码。

2 个答案:

答案 0 :(得分:0)

我想你的csv会是这样的:

user1, hash_pass_u1
user2, hash_pass_u2
user3, hash_pass_u3
...

解决方案前只需注意一点。您正在导入Python的CSV模块,并且您没有在代码中使用它,这是一个愚蠢的导入,只需使用它。

解决方案很简单

import csv

file = 'yourcsv.csv'
found = False
username = input('Write your username: ')
password_csv = None
with open(file, newline='') as csvfile:
   reader = csv.reader(csvfile, delimiter=',')
   for row in reader:
      # row[0] is the first element, the username and row[1] the hash of the password
      if row[0] == username:
         password_csv = row[1]
         found = True
         break
if not found:
   print('The username is not in our DB.')

while True:
   passw = input('Let me your password: ')
   hash_passw = your_method_to_get_the_hash(passw)
   if hash_passw == password_csv:
      print('Congrats, you are logged.')
      break
   else:
      print('Wrong password dude, try again.') 

通过这种方式,您只需阅读一次文件即可使用CSV模块。

我假设你的CSV格式如果是另一种格式很容易改变这个解决方案的实现。如果您需要有关CSV模块的帮助,请参阅此处的文档,python2python3

解释你做错了什么。

当您执行以下句子时:

csv = open('inlog.csv', 'r').read().split('\n')[1].split(';')

您正在打开文件,读取所有文件,然后按\n字符拆分文件,这样您将获得以下列表['user1;pass1';'user2;pass2','user3;pass3',...],您在那里执行的最后一步是选择第二个带有[1]的元素,其结果将是字符串'user2;pass2'。但是这个陈述没有在这里完成,还有另一个分组会给你列表['user2','pass2']

因此,您要比较用户名是admin或列在['user2','pass2']列表中。当您尝试比较密码时会发生同样的情况,但这次您选择了第三个元素。

答案 1 :(得分:0)

with open('Usernames.txt', 'r') as f:
   content = f.readlines()
   index = [x for x in range(len(content)) if password in content[x].lower()]
       index = (str(index)[1:-1])
       if index == '':
            print("user not found")
       else:
            index = (int(index))
            with open('passwords.txt', 'r') as d:
               d = d.readlines()
               f = (d[index]).strip()
               if password == f:
                    print("found password")

如果我想使用单独的文件(txt)来包含用户名和密码,我会这样做。它抢线。用户名打开,然后并行输入密码