首页 > 解决方案 > 如何修复用于验证外部文件的代码?

问题描述

我创建了一个身份验证程序,它扫描目录中包含用户请求的内容的文件,它在询问用户名时有效,但在询问密码时无效。我不知道该怎么办?用户名成功时打印欢迎,即使密码正确也不打印欢迎

userAuthen = input("What is your username? ")
path = r"C:\Users\JOSHUA\Desktop\Python stuff\usernames"
directories = os.scandir(path)
with directories as dirs:
    for entry in dirs:
        with open(entry.path,"r") as fileUser:
            contentsUser = fileUser.read()
            if contentsUser == userAuthen:
                print("Welcome!")
                break


passAuthen = input("What is your password? ")
path = r"C:\Users\JOSHUA\Desktop\Python stuff\passwords"
directories = os.scandir(path)
with directories as dirs:
    for entry in dirs:
        with open(entry.name,"r") as filePass:
            contentsPass = filePass.read()
            if contentsPass == passAuthen:
                print("Welcome!")
                break

标签: pythonfileauthentication

解决方案


您的代码可能不起作用,因为当您在 python 中读取文件时,file.read()它还包含新行分隔符\n。当您使用普通文本编辑器打开文件时,您看不到这些分隔符。但他们在那里。使用时,file.read().splitlines()您会得到一个所有行都没有\n分隔符的数组。

试试这个:

import os

userAuthen = input("What is your username? ")

path = r"C:\Users\JOSHUA\Desktop\Python stuff\usernames"
directories = os.scandir(path)

username_found = False
password_found = False

with directories as dirs:
    for entry in dirs:
        with open(entry.path, "r") as fileUser:
            contentsUser = fileUser.read().splitlines()
            for username in contentsUser:
                if username == userAuthen:
                    username_found = True
                    break

passAuthen = input("What is your password? ")
path = r"C:\Users\JOSHUA\Desktop\Python stuff\passwords"
directories = os.scandir(path)

with directories as dirs:
    for entry in dirs:
        with open(entry.path, "r") as filePass:
            contentsPass = filePass.read().splitlines()
            for password in contentsPass:
                if password == passAuthen:
                    password_found = True
                    break

if username_found and password_found:
    # Code if login was successful
    print("Welcome!")

推荐阅读