如何检查 txt 文件中的每一行是否有正确的用户名和密码

发布于 2025-01-17 21:55:15 字数 923 浏览 3 评论 0原文

此任务的目的是检查user.txt文件中的每一行(其中包含一个列表 用户名和密码)

然后,程序应将输入用户名和密码与TXT文件中的每一行进行比较 如果找不到任何匹配的用户名和密码,它将显示一个错误消息,如果循环应破坏

user.txt
Steve steve123
Eddie ed123
Dexter dex123

我可以想到的任何事情。

尽管我几乎可以肯定的是,问题出现在循环中。

看来它仅比较TXT文件中的最后一行,

我仍然对此非常新颖,因此请有怜悯::)

有关如何让程序来检查用户输入是否匹配每个单独的文本线的任何提示。 另外,TXT文件可以在任何时候更改或添加到任何时候,如果没有,我可以使用行索引来完成此操作。


content = ""
user_List = []


while True:

    print("Username")
    username = input()
    print("Password")
    password = input()
    name_pass = username + " " + password

    with open("user.txt" , "r+") as f:
        for line in f:
            if name_pass == line:
                
                x = False
            else:
                x = True

    if x == False:
        print("Wellcome")
        break
    elif x == True:
        print("Incorrect Username or Password \nPlease try again")


    

The purpose of this task is to check each line in the user.txt file (that contains a list
of usernames and passwords)

The program should then compare the input username and password to each line in the txt file
if it doesn't find any matching username and password it displays an error message if it does the loop should break

user.txt
Steve steve123
Eddie ed123
Dexter dex123

I tried just about anything I could think of.

Although I'm almost dead certain the problem is in the loop.

It seems that it only compares the last line in the txt file

I'm still pretty new to this so please have mercy :)

Any tips on how I can get the program to check if the user input matches each individual line of text.
Also , The txt file can change or be added to at any point , if not I could have accomplished this using line indexing.


content = ""
user_List = []


while True:

    print("Username")
    username = input()
    print("Password")
    password = input()
    name_pass = username + " " + password

    with open("user.txt" , "r+") as f:
        for line in f:
            if name_pass == line:
                
                x = False
            else:
                x = True

    if x == False:
        print("Wellcome")
        break
    elif x == True:
        print("Incorrect Username or Password \nPlease try again")


    

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

权谋诡计 2025-01-24 21:55:18

问题必须是,当您迭代线路时,该行最终会带有\ n,因为在您的txt文件中,有一个返回,该返回是嵌入的,没有您看到\ n! 。为了验证这一点,您可以添加此语句«  print(reter(line)) »»在f »中的« 之后陈述。 reper函数(表示)将向您展示字符串而不会摆脱\ n。
如果是这种情况,您只能这样验证:如果name_pass == line [: - 1],我很确定您了解最后一个语句ahah;)

The problem has to be that when you iterate over the line , the line will end up with an \n because in your txt file there is a return which is embeded without you see the \n! . To verify this you can add this statement « print(repr(line)) » after the « for line in f » statement. The repr function(representation) will show you the string without getting rid of the \n.
And if this is the case you simply can verify like this : if name_pass == line[:-1], im pretty sure you understand this last statement ahah;)

筱武穆 2025-01-24 21:55:18

我更改了变量x,现在称为deny_access。无论如何,我认为问题在于for循环。在您的代码中,您会在每行中修改变量x,因此在for循环之后,重要的唯一行是最后一个。这是错误的。
这是修复代码的方法:

content = ""
user_List = []


while True:

    print("Username")
    username = input()
    print("Password")
    password = input()
    name_pass = username + " " + password

    with open("user.txt" , "r+") as f:
        deny_access = True
        for line in f:
            if name_pass == line:
                deny_access = False
                break

    if deny_access == False:
        print("Wellcome")
        break
    elif deny_access == True:
        print("Incorrect Username or Password \nPlease try again")

注意:使用此修复程序应该起作用。但这并不意味着它是安全的,或者这是一个很好的编程实践。我的意思是,如果这是您正在测试要学习的内容或小型项目的代码,那是完美的。但是,如果它用于生产或更大的东西,则必须改变很多事情。

I changed the variable x, now it's called deny_access. Anyway, I think the problem is in the for loop. In your code you modify the variable x in every line, so after the for loop the only line that matters is the last. This was wrong.
Here is how to fix the code:

content = ""
user_List = []


while True:

    print("Username")
    username = input()
    print("Password")
    password = input()
    name_pass = username + " " + password

    with open("user.txt" , "r+") as f:
        deny_access = True
        for line in f:
            if name_pass == line:
                deny_access = False
                break

    if deny_access == False:
        print("Wellcome")
        break
    elif deny_access == True:
        print("Incorrect Username or Password \nPlease try again")

Note: With this fix it should work. But that doesn't mean it's safe or that it's a good programming practice. What I mean is that if this is a code that you are testing things to learn or a small project, it is perfect. But if it goes to production or something bigger, you have to change a bunch of things.

内心旳酸楚 2025-01-24 21:55:18

你在这里,伙计。
尝试一下。我总是在这种情况下这样做。
如果您要模拟登录页面之类的内容,则可以将此代码用作示例。另外,您可以看到使用文本文件在类似条件下保存密码的示例。

import os
import shutil
def action():
    action = int(input("what you want to do?\n1 for create account\n2 for delete existed account\n: "))
    if action == 1:
        signup()
    elif action == 2:
        delete_account()
    else:
        print("no valid option has been selected")

def delete_account():
    username = input("enter your username: ")
    password = input("enter your password: ")
    if os.path.isdir(f"./{username}_account"):
        with open(f"./{username}_account/password", 'r') as passfile:
            pass_containment = passfile.read()
        if password == pass_containment:
            shutil.rmtree(f"./{username}_account")
            print("your account has been removed")
        else:
            print("username or password is not correct")
    else:
        print("username or password is not correct")

def signup():
    username = input("set a username: ")
    password = input("set a password: ")
    conf_password = input("confirm your password: ")
    if username == password:
        print("password and username cannot be same")
    else:
        if os.path.isdir(f"./{username}_account"):
            print("account has been already existed, choose another username")
        else:
            if password == conf_password:
                os.mkdir(f"{username}_account")
                with open(f"./{username}_account/username", 'w') as userfile:
                    userfile.write(username)
                with open(f"./{username}_account/password", 'w') as passfile:
                    passfile.write(str(password))
            else:
                print("passwords are not same")
action()

here you are, man.
try this. I always do that in this condition.
if you are trying to simulate something like login page, you can use this code as a sample. also you can see examples of using text files to save password in similar conditions.

import os
import shutil
def action():
    action = int(input("what you want to do?\n1 for create account\n2 for delete existed account\n: "))
    if action == 1:
        signup()
    elif action == 2:
        delete_account()
    else:
        print("no valid option has been selected")

def delete_account():
    username = input("enter your username: ")
    password = input("enter your password: ")
    if os.path.isdir(f"./{username}_account"):
        with open(f"./{username}_account/password", 'r') as passfile:
            pass_containment = passfile.read()
        if password == pass_containment:
            shutil.rmtree(f"./{username}_account")
            print("your account has been removed")
        else:
            print("username or password is not correct")
    else:
        print("username or password is not correct")

def signup():
    username = input("set a username: ")
    password = input("set a password: ")
    conf_password = input("confirm your password: ")
    if username == password:
        print("password and username cannot be same")
    else:
        if os.path.isdir(f"./{username}_account"):
            print("account has been already existed, choose another username")
        else:
            if password == conf_password:
                os.mkdir(f"{username}_account")
                with open(f"./{username}_account/username", 'w') as userfile:
                    userfile.write(username)
                with open(f"./{username}_account/password", 'w') as passfile:
                    passfile.write(str(password))
            else:
                print("passwords are not same")
action()
遗忘曾经 2025-01-24 21:55:18

首先,文本文件中的每一行都以新行结尾,因此为了匹配 name_pass 变量,您需要在其末尾添加新行。

name_pass = username+" "+password+"\n"

其次,if 语句的逻辑不正确,您需要在找到后中断循环匹配,这样 x 就不会再次被错误值覆盖

    with open("user.txt", "r+") as f:
    for line in f:
        if name_pass == line:
            x = False
            break
        else:
            x = True

firs of all each line in the text file ends with a new line so for name_pass variable to match u need to add new line to the end of it

name_pass = username+" "+password+"\n"

second the logic of the if statements is not right u need to break the loop after u find a match so the x doesn't get overwrite again with false value

    with open("user.txt", "r+") as f:
    for line in f:
        if name_pass == line:
            x = False
            break
        else:
            x = True
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文