Does my program sometimes write extra] or} at the end of the data in the json file?

I wrote a note taking tool for myself as my first program. In fact, it works very well, but sometimes the program will write additional ones ]either }at the end listor dictstored inside the specified file json.

This does not happen often, and I think it only happens when I write new lines of code or by modifying existing lines that read / write to specified files. I'm not 100% sure, but here is what it looks like.

For example, I have one liststored in a file, and I use a flag indent=""to make sure it writes files that it reads a little for me if I ever have to edit the specified files. Sometimes when I run my program after changing the code or adding the code, I get an error message in which the file contains "additional data". The error looks something like this:

    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 6 column 2 (char 5791)

and the cause of the error will be something like this:

[
"Help",
"DataTypes",
"test",
"Variables",
]] # the error would be cause by this extra ] at the end of the list

I don’t understand why the program sometimes adds and adds] or} at the end of the data in my json files?

Is there something I am doing wrong when I open a file or dump to a file?

Here are some sections of code that I use to open files and dump files:

path = "./NotesKeys/"
notebook = dict()
currentWorkingLib = ""
currentWorkingKeys = ""
#~~~~~~~~~~~~~~~~~~~< USE TO open all files in Directory >~~~~~~~~~~~~~~~~~~~
with open("%s%s"%(path,"list_of_all_filenames"), "r") as listall:
    list_of_all_filenames = json.load(listall)

def openAllFiles(event=None):
    global path
    for filename in os.listdir(path):
        with open(path+filename, "r+") as f:
            notebook[filename] = json.load(f)
openAllFiles()

. e1Current, e1allcase, e2Current, , (dict key) , , , . .:

: .

#~~~~~~~~~~~~~~~~~~~< UPDATE selected_notes! >~~~~~~~~~~~~~~~~~~~

            dict_to_be_updated = notebook[currentWorkingLib]
            dict_to_be_updated[e1Current] = e2Current
            with open("%s%s"%(path,currentWorkingLib),"r+") as working_temp_var:
                json.dump(dict_to_be_updated, working_temp_var, indent = "")

, , , .

- ? - json ?

+4
1

-, r+:

with open("%s%s"%(path,currentWorkingLib),"r+") as working_temp_var:

, , , , , . , .

, , r+, , :

>>> with open('/tmp/demo', 'w') as init:
...     init.write('The quick brown fox jumps over the lazy dog\n')
...
44
>>> with open('/tmp/demo', 'r+') as readwrite:
...     readwrite.write("Monty Python flying circus\n")
...
29
>>> with open('/tmp/demo', 'r') as result:
...     print(result.read())
...
Monty Python flying circus
r the lazy dog

. w, :

with open("%s%s"%(path,currentWorkingLib), "w") as working_temp_var:

, 0, JSON.

+5

Source: https://habr.com/ru/post/1675812/


All Articles