簡體   English   中英

如何檢查 Python 文件中的用戶輸入?

[英]How to check user input from a file in Python?

您好,我有一個如下所示的 txt 文件:

name1, password1
name2, password2,
name3, password3,
and so on...

我需要檢查用戶輸入的名稱和密碼是否與此文件中存儲的相同。 我查看了這個答案,但沒有幫助: answ1 answ2這是我的代碼。 如果我輸入正確的名稱和密碼,while 循環仍會提示我輸入用戶信息:

name = input('Enter username: ')
password = input('Enter password: ')


with open('file.txt','r') as f: 
    data = f.readlines()
        
    for line in data:
        names =line.split(' ')[0]
        passwords = line.split(' ')[1]
      
        while name not in names or password not in passwords:
            name = input('Enter a valid username: ')
            password = input('Enter a valid password: ')

現在你正在測試每一行的用戶輸入:輸入不能匹配每一行

您最好將這些對存儲在dict中,這將有助於驗證


同時測試兩者

with open('file.txt', 'r') as f:
    data = f.readlines()

credentials = {}
for line in data:
    name, password = line.strip().split(",")
    credentials[name] = password

name = input('Enter a username: ')
password = input('Enter a password: ')
while name not in credentials or credentials[name] != password:
    name = input('Enter a valid username: ')
    password = input('Enter a valid password: ')

單獨測試

name = input('Enter a username: ')
while name not in credentials:
    name = input('Enter a valid username: ')

password = input(f'Enter a password for user {name}: ')
while credentials[name] != password:
    password = input(f'Enter a valid password for user {name}: ')

由於數據文件中逗號的使用不一致,您需要采取一些額外的步驟。

with open('file.txt') as indata:
    DB = dict(map(lambda e: e.rstrip(','), line.split()) for line in indata)
    while True:
        name = input('Enter username: ')
        password = input('Enter password: ')
        if DB.get(name) == password:
            break # username / password is valid
        print('Invalid username or password\a')

在文件輸入的幫助下。 input() 方法,我們可以獲得文件作為輸入,並且可以使用 fileinput 更新和 append 文件中的數據。 輸入法。 返回:返回文件的數據

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM