如何修复用于验证外部文件的代码



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

userAuthen = input("What is your username? ")
path = r"C:UsersJOSHUADesktopPython stuffusernames"
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:UsersJOSHUADesktopPython stuffpasswords"
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

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

试试这个:

import os
userAuthen = input("What is your username? ")
path = r"C:UsersJOSHUADesktopPython stuffusernames"
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:UsersJOSHUADesktopPython stuffpasswords"
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!")

相关内容

最新更新