如何在 python 中比较文件中的信息

问题描述 投票:0回答:1

所以我有一个文件,我想将它与我的用户输入进行比较,以便该文件的信息可能等于用户输入的内容。在 reg_login.txt 中它包含信息。

 Username = Emmanuel, Password = emman
 Username = Emmanuel, Password = em

我想让代码比较用户的输入和 reg_login.txt 并确保它在文本文件中的内容与程序相同。如果不相等则要求用户一次又一次地输入,直到 reg_login.txt 与用户的输入相等

当我写代码的时候

username1 = input("What is your username?: ")

password2 = input("What is your password!")

reg = open("reg_login.txt")

if username1 = "Username =" = open("reg_login.txt")

if password2 = "Password =" = open("reg_login.txt")

我希望程序能够比较字符串和变量。

python user-input
1个回答
0
投票

比较字符串和变量

open()
单独不读取文件。您将需要遍历这些行。

例如,

match = False
while not match:
  user = input("What is your username?: ")
  password = input("What is your password!")

  with open("reg_login.txt") as f:
    for line in f:
      if line.startswith(f'Username = {user},') and line.rstrip().endswith(f'Password = {password}'):
        print('Matching user!')
        match = True
        break

print(f'Hello {user}.')

请记住 - 永远不要将密码存储或输入为易于阅读的明文值。

© www.soinside.com 2019 - 2024. All rights reserved.