Home > Software design >  A problem when writing in json file (python)
A problem when writing in json file (python)

Time:10-23

I'm new to kinda python so this is my code (a part of it) :

import json
from time import sleep as sl

logs = open('C://Users//pc//Desktop//tikmoh//Dev//projects//other//Python//log and reg sys//users.json','r ')
data = json.load(logs)

def reg():
    def remove_quotes(x=str):
        x = x.replace("\"","").replace('\'',"")
        return x

    print("========================================================================")
    print("|| WARNING : Don't use quotes \" or ' , it will be automaticly removed ||")
    print("========================================================================")
    sl(1.4)
    username = str(input("hello there , ur username : "))
    username = remove_quotes(username)
    sl(0.6)
    pw = str(input("okay , ur password now : "))
    pw = remove_quotes(pw)
    sl(0.6)
    confirm_pw = str(input("confirm ur password : "))
    confirm_pw = remove_quotes(confirm_pw)
    sl(1)
    while pw != confirm_pw :
        print('\nur password cofirmation doesn\'t match the Password !')
        sl(0.6)
        pw = str(input("rewrite the password , here :"))
        pw = remove_quotes(pw)
        sl(0.6)
        confirm_pw = str(input("confirm the password , here :"))
        confirm_pw = remove_quotes(confirm_pw)
        sl(1)
    for x in range(len(data)):
        if username == data[x]["username"] and pw == data[x]["pw"]:
            print("this account already exists !")
            break
    else:
        new_user = {"username" : username , "pw" : pw}
        data.append(new_user)
        new_logs_list = json.dumps(data , indent=2)
        logs.truncate(0)
        logs.write(new_logs_list)
        print('\nYou Are Succesfully Registered sir/ma\'am !!!')

I have a users.json file where I store data , the code works perfectly but when it comes to this part of code (in the else statement):

for x in range(len(data)):
        if username == data[x]["username"] and pw == data[x]["pw"]:
            print("this account already exists !")
            break
else:
    new_user = {"username" : username , "pw" : pw}
    data.append(new_user)
    new_logs_list = json.dumps(data , indent=2)
    logs.truncate(0)
    logs.write(new_logs_list)
    print('\nYou Are Succesfully Registered sir/ma\'am !!!')

a problem happens in the users.json file , it will write a weird thing (the new data is stored tho): IMAGE1

along with this error : IMAGE2

sorry , I don't know how to use StackOverFlow properly (ik you hate Images or smth like that)

CodePudding user response:

Apart from the logic errors, try using seek() instead of truncate().

  • Related