python - 添加后程序在文件中找不到新对象
问题描述
我制作了这个程序,它给出了您要求的对象(在 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.
解决方案
问题是在保持文件打开的脚本中有一个 Variable = getjson("file") 。所以我删除了它并将它添加到需要它的函数中。所以它只在我运行这些功能时打开文件。
推荐阅读
- javascript - Internet Explorer 呈现问题。(HTML CSS JS)
- .net-core - F# Interactive (fsi.exe) 支持.Net Core SDK (v3.1.100.14727)
- sql - 如何使用 AWS IoT Core 中的 sql 语句解码 JSON 列表?
- android - 像 Spotify 这样的按钮反馈
- django - 模板不存在 | django 3.0.1,python 3.6
- python - Keras:转置 Conv2D 层的内核以便在另一个 Conv2D 层中重用
- python - 如何通过构造函数实现依赖注入 - Python
- swift - 如何在没有窗口的情况下使用 Swift 在 macOS 上检测 Caps Lock 状态?
- java - 无法用毕加索检索图像frm firebase
- c - 在 C 中使用 fork 创建新进程时出现分段错误