我的程序有时会在json文件中的数据末尾写一个额外的]或}?

Mik*_*SMT 4 python json dictionary file list

我为自己写了一个笔记工具作为我的第一个程序.它实际上在大多数情况下工作得很好,但有时程序会写一个额外的]或者}在所述文件的内部list或dict存储在所述json文件的内部.

它并不经常发生,我认为只有当我编写新的代码行或更改读取/写入所述文件的现有行时才会发生这种情况.我不是100%肯定,但这就是它的样子.

例如,我有一个list存储在一个文件中,我使用该indent=""标志来确保,因为它编写文件,如果我必须编辑所述文件,它对我来说更具可读性.有时在更改某些代码或添加代码后运行我的程序时,我收到一条错误,指出文件中有"额外数据".错误看起来像这样:

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

并且错误的原因将是这样的:

[
"Help",
"DataTypes",
"test",
"Variables",
]] # the error would be cause by this extra ] at the end of the list
Run Code Online (Sandbox Code Playgroud)

我不明白为什么程序有时会在我的json文件中的数据末尾添加和添加]或}?

当我打开文件或转储到文件时,我有什么问题吗?

以下是我用于打开文件和转储到文件的代码的一些部分:

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()
Run Code Online (Sandbox Code Playgroud)

这是我如何更新文件中的数据.只需忽略e1Current, e1allcase, e2Current它们用于保存用户输入文件名(dict键)的小写字母在存储注释的字典中的小写,并保持用户为显示列表估算的情况.这不应该与文件读写问题有关:

编辑:删除每个评论者请求的不相关代码.

#~~~~~~~~~~~~~~~~~~~< 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 = "")
Run Code Online (Sandbox Code Playgroud)

我知道如何打开文件并使用数据以及如何将数据转储到所述文件,并根据新转储的数据更新程序变量中加载的内容.

我在这个过程中遗漏了哪些重要内容?我应该做些什么来确保json文件中的数据完整性吗?

Mar*_*ers 5

您正在以读写模式打开文件r+:

with open("%s%s"%(path,currentWorkingLib),"r+") as working_temp_var:
Run Code Online (Sandbox Code Playgroud)

这意味着您将写入已包含数据的文件,有时现有数据比您现在写入文件的数据长.这意味着你最终会得到一些尾随数据.

您可以通过将较短的演示字符串写入文件,然后使用较少的数据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's flying circus\n")
...
29
>>> with open('/tmp/demo', 'r') as result:
...     print(result.read())
...
Monty Python's flying circus
r the lazy dog
Run Code Online (Sandbox Code Playgroud)

不要这样做.使用w写入模式,以便首先截断文件:

with open("%s%s"%(path,currentWorkingLib), "w") as working_temp_var:
Run Code Online (Sandbox Code Playgroud)

这可确保在编写新的JSON文档之前将文件缩减为0.