首页 > 解决方案 > 添加后程序在文件中找不到新对象

问题描述

我制作了这个程序,它给出了您要求的对象(在 JSON 中)文件的值。我创建了一个向 JSON 文件添加新对象的函数。一切正常,但是当我添加一个对象时,它会被添加到文件中,但是当我尝试询问新对象时它没有找到它,好像它不存在一样,但是当我检查文件时,我可以看到物体在那里。我唯一能做的就是关闭程序并重新打开它,以便它识别添加的对象。有没有办法让程序刷新或重新打开文件,以便它找到添加的对象而无需关闭/打开。下面是我的代码。

#first the program open the file 
def getjson(filepathname):
    with open(filepathname, 'r') as fp:
        return json.load(fp)

#this add new object to the file then closing it and flush so it make the changes to the file
def confirm():
    newentry = {entered_word.get(1.0, END).rstrip("\n")  : newword_def.get(1.0, END).rstrip("\n")}

    with open("dictionary.json", "r+") as file:
        data = json.load(file)
        data.update(newentry)
        file.seek(0)
        json.dump(data, file)
        file.flush()
        file.close()


 root.mainloop()
 #I didn't add the rest of the script because it's all just GUI stuff and it works fine.

标签: pythonjsonfiletkinter

解决方案


问题是在保持文件打开的脚本中有一个 Variable = getjson("file") 。所以我删除了它并将它添加到需要它的函数中。所以它只在我运行这些功能时打开文件。


推荐阅读