简体   繁体   English

如何将多行文本文件分解为可以迭代的列表,以检查 python 中的输入 == 文本文件?

[英]How do I break a multiple line text file, into a list which can be iterated through to check if input == text file in python?

When running the Code I get a logic error where it continues to throw the first if statement error "Error! Username does not exist."运行代码时,我收到一个逻辑错误,它继续抛出第一个 if 语句错误“错误!用户名不存在”。 I need to be able to log in as admin and then add users by adding them to a .txt file, after which, if the program is run again, I can log in either by admin or one of the new users created in the txt file.我需要能够以管理员身份登录,然后通过将用户添加到 .txt 文件来添加用户,之后,如果程序再次运行,我可以通过管理员或在 txt 中创建的新用户之一登录文件。 I cant seem to get it split properly in order for the loop to iterate through the list correctly when login in.我似乎无法正确拆分它,以便循环在登录时正确遍历列表。

Example:例子:

print(new_lines) = [['admin', 'adm1n'], ['kevin', 'kev1n'], ['dorothy', '1234']]打印(new_lines)= [['admin','adm1n'],['kevin','kev1n'],['dorothy','1234']]

.txt file content with each entry on new line = admin,adm1n\\n kevin,kev1n\\n dorothy,1234 .txt 文件内容,每个条目都在新行 = admin,adm1n\\n kevin,kev1n\\n dorothy,1234

Code thus far:到目前为止的代码:

import time

#User input of username and password

user_name = input("Username:\n")
user_pass = input("Password: \n")

#Opening document

with open("user.txt", "r+", encoding = "utf-8-sig") as f:
    
    new_lines = []
    for line in f:
        new_line = line.strip()
        new_lines.append(new_line.split(","))
        
    print(new_lines)

    #Loop to enter user name and password
    for x in new_lines:
        for y in x:
            if user_name != new_lines[:][0]:
                print("Error! Username does not exist.")
                user_name = input("Username:\n")
                user_pass = input("Password: \n")
                
            elif user_pass != new_lines[:][1]:
                print("Error! Incorrect password.")
                user_name = input("Username:\n")
                user_pass = input("Password: \n")
                
            else:
                print("Welcome back!")
                break
        break
        
    #User options to choose from        
    user_choice = input("""\nPlease select one of the following options:
                            \nr - register user
                            \na - add task 
                            \nva - view all tasks
                            \nvm - view my tasks
                            \ne - exit
                            \nAnswer: """)

I recommend reformatting the code a little to make it easier to find if the username exists and if the password is correct.我建议稍微重新格式化代码,以便更容易找到用户名是否存在以及密码是否正确。

import time

#User input of username and password

user_name = input("Username:\n")
user_pass = input("Password: \n")

#Opening document

with open("user.txt", "r+", encoding = "utf-8-sig") as f:
    
    new_lines = []
    for line in f:
        new_line = line.strip()
        new_lines.append(new_line.split(","))

usernames = [acc[0] for acc in new_lines]
pws = [acc[1] for acc in new_lines]

while True:
    if user_name not in usernames:
        print("Error! Username does not exist.")
        user_name = input("Username:\n")
        user_pass = input("Password: \n")
    else:
        pw_index = usernames.index(user_name)
        if user_pass != pws[pw_index]:
            print("Error! Incorrect password.")
            user_name = input("Username:\n")
            user_pass = input("Password: \n")
        else:
            print("Welcome back!")
            break

#User options to choose from        
user_choice = input("""\nPlease select one of the following options:
                        \nr - register user
                        \na - add task 
                        \nva - view all tasks
                        \nvm - view my tasks
                        \ne - exit
                        \nAnswer: """)

You have a logic error in the loop - you seem to compare every line in the text file to the username and password provided, and state an error if they dont match - ignoring the fact that the user may not be on the first line of the file.您在循环中有一个逻辑错误 - 您似乎将文本文件中的每一行与提供的用户名和密码进行比较,如果它们不匹配则说明错误 - 忽略用户可能不在第一行的事实文件。 The error should only be displayed if you went through the entire file and didnt find the user, or found the user but the password mismatches.仅当您浏览整个文件但未找到用户,或找到用户但密码不匹配时,才会显示该错误。

Also, I dont think you want the inner loop at all, you declare x and y but dont use them, have you tried printing them and checking what they hold?另外,我认为您根本不需要内部循环,您声明了 x 和 y 但不使用它们,您是否尝试过打印它们并检查它们保存的内容?

Anyway, this is the outline of how I think the loop should look无论如何,这是我认为循环应该看起来的轮廓

found = False
for current_user, current_password in new_lines:
    if current_user == user_name:
        if current_password == user_pass:
            print("Welcome back!")
            found = True
        else:
            print("Error! Incorrect password")
       break
if not found:
    print("Error! Username does not exist.")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从用户输入中搜索单词列表的文本文件,并打印包含这些单词的行? - how can i search a text file of list of words from user input and print the line which contains these words? 如何使用python编辑文本文件中的特定行而不将文本文件中的所有内容转换为列表? - How do I edit a specific line in a text file with python without converting everything in the text file into a list? 如何使用Python将数据附加到包含换行符的文本文件? - How can I append data to a text file with a line break using Python? 如何用 Python 中包含相同数据的单行文本替换文件中的多个 3 行文本块 - How can I replace multiple 3 line blocks of text in a file with a single line of text containing the same data in Python 如何使用 input() 从文本文件中获取输入数据的 python 的代码? - How do I make the code of python which get the input data from a text file with using input()? 在Python中,如何检查文件是文本文件? - In Python, how do I check that a file is a text file? 如何运行将文本文件作为输入的python文件? - How do I run a python file that takes a text file as input? 如何在python中通过文本文件获取输入? - How to take input through text file in python? Python:如何检查文本文件,将其与另一个文本文件中的每一行进行比较,并打印不匹配的行 - Python: How to check a text file, compare it to each line in another text file, and print the lines that do not match 我如何使用文本文件中的一行作为python中的函数输入? - how do i use a line from a text file as a function input in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM