首页 > 解决方案 > 将数据存储在 .txt 文件中并检索它

问题描述

我正在尝试制作某种登录系统,我有它,如果用户名和密码在 test.txt 中(有多个),它应该让你登录,我什至没有通过验证是否用户名和密码在 txt 文件中,它破坏了我,我不知道该怎么做,我尝试了几个小时,我做到了“如果你在文本文件中找到这个用户名,给我行号并检查如果密码这个密码在用户名的同一行,(我使用split(',')),如果输入的电子邮件和密码都存在于txt文件中并且在同一行中,那么..(没有做还没有)。

所以这让我很困惑,有很多错误,如果没有错误,那么它不能像我预期的那样工作,这是我的意大利面条代码

def test():
    with open('test.txt', 'r') as f:
        for num, line in enumerate(f,1):
            username = line.split(',')
            if username in num:
                 if username == q1:
                    print("found user in line: " + num)
                    Line = num
                    password = line.split(',')
                    if password in Line:
                        if password == q2:
                            print("found pass in line: " + num)

有人可以帮我解决这个问题并向我解释在 .txt 文件中存储数据的工作原理以及如何检索它们吗?YouTube 和 google 真的没有多大帮助,如果你能推荐一个也很酷的视频,因为我现在很困惑,我剩下的就是尝试 MongoDB,因为它已经具有检索数据和存储它的功能内置

但由于它在我的电脑上而不是在互联网上,我认为我不需要 MongoDB,所以这对于本地测试来说是一种过度杀伤力

标签: pythonauthenticationtxt

解决方案


使用 json,您可以通过以下方式完成它:

JSON文件

{
"user1":{"password":"123456"},
"user2":{"password": "abcde"}
}

Python

import json

def test(username, password):
    with open("answer.json", "r") as read_it: 
        data = json.load(read_it) 
    if data[username][password] == '123456':
        print('User found!')
    else:
        print('User or password doesn\'t exist')
          
 test('user1', 'password')

推荐阅读