python - 如何修复用于验证外部文件的代码?
问题描述
我创建了一个身份验证程序,它扫描目录中包含用户请求的内容的文件,它在询问用户名时有效,但在询问密码时无效。我不知道该怎么办?用户名成功时打印欢迎,但即使密码正确也不打印欢迎
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
解决方案
您的代码可能不起作用,因为当您在 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!")
推荐阅读
- python - 无法在响应中可视化元素值(python 请求)
- r - 根据行中的值将一行分成多个
- reactjs - 标签'style amp-custom'的父标签是'form',但它只能是'head'
- firebase-cloud-messaging - 电报中firebase消息的用途是什么
- r - 拟合数据并在 R 中获得定义的最小值
- ruby-on-rails - Rails respond_with 正确显示带有验证但带有索引路径 URL 的表单
- android - 未创建任何 firebase 应用程序“默认” - 调用 firebase.initializeapp()
- haskell - 在`first`的严格版本中两次调用`seq`
- c++ - bool operator() 有什么作用?
- java - 什么是纯 Java 中 Guice 的 FactoryModuleBuilder 的替代品?