Python - 匹配来自外部文件的数据(用户名密码)
Python - matching data from an external file (username password)
我知道这与换行标记有关,但为什么我的程序无法在我的外部文件中找到 username/password 匹配项?
username = input("Please enter your username: ")
password = input("Please enter your password: ")
file = open("UsernamesPasswords.txt", "r")
for loop in file:
line = file.readline()
data = line.split(",")
print(data)
if username == data[0] and password == data[1]:
print("That's a match")
else:
print("That's not a match!")
break
file.close()
假设 UsernamesPasswords.txt
看起来像这样:
username_1,password_1
username_2,password_2
username_3,password_3
我们可以写代码:
username_input = input("Please enter your username: ")
password_input = input("Please enter your password: ")
file = open("UsernamesPasswords.txt", "r")
contents = file.read()
file.close()
for line_index, line in enumerate(contents.splitlines()):
parts = line.strip().split(",")
if len(parts) != 2:
# Incorrect line
continue
username, password = parts
if username == username_input and password == password_input:
print(f"That's a match, at line {line_index}.")
else:
print(f"That's not a match, at line {line_index}.")
break
我知道这与换行标记有关,但为什么我的程序无法在我的外部文件中找到 username/password 匹配项?
username = input("Please enter your username: ")
password = input("Please enter your password: ")
file = open("UsernamesPasswords.txt", "r")
for loop in file:
line = file.readline()
data = line.split(",")
print(data)
if username == data[0] and password == data[1]:
print("That's a match")
else:
print("That's not a match!")
break
file.close()
假设 UsernamesPasswords.txt
看起来像这样:
username_1,password_1
username_2,password_2
username_3,password_3
我们可以写代码:
username_input = input("Please enter your username: ")
password_input = input("Please enter your password: ")
file = open("UsernamesPasswords.txt", "r")
contents = file.read()
file.close()
for line_index, line in enumerate(contents.splitlines()):
parts = line.strip().split(",")
if len(parts) != 2:
# Incorrect line
continue
username, password = parts
if username == username_input and password == password_input:
print(f"That's a match, at line {line_index}.")
else:
print(f"That's not a match, at line {line_index}.")
break