我正在学习如何在python中更新、编写和读取json文件。
当我用异常处理更新我的json文件时,它会产生一个错误:
Exception in Tkinter callback Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/tkinter/__init__.py",
line 1921, in __call__
return self.func(*args) File "/Users/montekkundan/Downloads/coding/python/password-manager/main.py",
line 53, in save
data = json.load(data_file) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/__init__.py",
line 293, in load
return loads(fp.read(), File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/__init__.py",
line 346, in loads
return _default_decoder.decode(s) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/decoder.py",
line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/decoder.py",
line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Process finished with exit code 0python函数:
def save():
website = website_entry.get()
email = email_entry.get()
password = password_entry.get()
new_data = {
website: {
"email": email,
"password": password,
}
}
if len(website) == 0 or len(password) == 0:
messagebox.showerror(title="Oops!", message="Please make sure you haven't left any fields empty.")
else:
try:
with open("data.json", "r") as data_file:
# Reading old data
data = json.load(data_file)
except FileNotFoundError:
with open("data.json", "w") as data_file:
json.dump(new_data, data_file, indent=4)
else:
# Updating old data with new data
data.update(new_data)
with open("data.json", "w") as data_file:
# Saving updated data
json.dump(data, data_file, indent=4)
finally:
website_entry.delete(0, END)
password_entry.delete(0, END)发布于 2022-03-14 15:19:50
检查文件中的内容--它似乎是空的。
空文件/字符串是不正确的JSON,它会引发错误。
当data找不到文件或读取文件有问题时,您应该创建新的空dict文件。
try:
with open("data.json", "r") as data_file:
# Reading old data
data = json.load(data_file)
except FileNotFoundError:
print("Problem: FileNotFoundError")
data = dict()
except json.JSONDecodeError:
print("Problem: JSONDecodeError")
data = dict()
finally:
# --- always ---
data.update(new_data)
with open("data.json", "w") as data_file:
# Saving updated data
json.dump(data, data_file, indent=4)
website_entry.delete(0, END)
password_entry.delete(0, END)https://stackoverflow.com/questions/71467769
复制相似问题