-2

I am struggling with reading the json file and checking if the username is registered and wether the password is correct. I tried to do it my self but it just work when the username and the password is in the first line. Please Help:

import json


print("LoginSystem @mvtthis")
myRL = input("Login or Register?")


if myRL == "Register":
    User = input("Username:") 
    PW = input("Password:")
    PW1 = input("Confirm Password:")

    if(PW == PW1):
        print("Registration successfully.")
        
        with open('LoginSystemData.json', 'a') as f:      
                f.write("\n" + User + "," + PW)
                
    else:
        print("Registration failed! Please confirm your Password correctly.") 

if myRL == "Login":
    User = input("Username:") 
    PW = input("Password:")
    success = False
    with open('LoginSystemData.json', 'r') as f: 
        for i in f:
            a,b = i.split(",")
            b = b.strip()
            a = a.strip()
            if(a==User and b==PW):
                print("Login successful")
            else:
                print("Login failed. Wrong Username or Password.")     
            f.close() 
            break
mvtthis
  • 1
  • 1
  • 1
    Does this answer your question? [Reading JSON from a file?](https://stackoverflow.com/questions/20199126/reading-json-from-a-file) – Joe Jun 13 '21 at 10:52
  • You did not create a valid json structured file. You have imported `json` library but did not even use it, You have to perform json read/write through the `json` module. Please spend some time reading through docs – Pythonizer Jun 13 '21 at 11:38

1 Answers1

-1

it works for me:Try this

...

if myRL == "Login":
    User = input("Username:") 
    PW = input("Password:")
    with open('LoginSystemData.json', 'r') as f: 
        readable = f.read() # --> you need to readable:str your file
        lines = readable.splitlines() # --> ['name,pw','name,pw','name,pw']
        user = list(filter(lambda l:l.split(',')[0] == User and l.split(',')[1] == PW,lines))
        if user:
               print("Login successful")
        else:
               print("Login failed. Wrong Username or Password.")     
        f.close()

actually the filter() doing like for loop: if you wanna check it : https://www.w3schools.com/python/ref_func_filter.asp