我正在寻找一种使用程序保存json数据的方法。现在,代码在每次启动时都会清除数据,但数据会保留下来,让我在运行代码时附加到该数据。我知道我必须先加载数据并将其再次写入文件,然后才能开始添加更多数据,但是我尝试过的一切都使我失败了。这是我的代码:
load_data_profile = {}
load_data_profile['profile'] = []
def save_profile():
load_data_profile['profile'].append({
'profile_name': profile_name_entry.get(),
'first_name': first_name_entry.get(),
'last_name': last_name_entry.get(),
'address': house_address_entry.get(),
'address2': house_address2_entry.get(),
'city': city_entry.get(),
'country': country_entry.get(),
'state': state_entry.get(),
'zip': zip_entry.get(),
'card_type': card_type_entry.get(),
'card_number': card_number_entry.get(),
'exp_month': card_exp_month_date_entry.get(),
'exp_year': card_exp_year_date_entry.get(),
'phone': phone_entry.get(),
'email': email_entry.get()
})
with open('profiles.txt', 'w', encoding='utf-8') as outfile:
json.dump(load_data_profile, outfile, indent=2)
这仅将信息写入文件。我遗漏了我尝试过的部分,因为我需要在这里重新输入所有内容。任何帮助都将不胜感激!
答案 0 :(得分:0)
使用json.load()
首先从文件中获取配置文件。
def save_profile():
try:
with open('profiles.txt', 'r', encoding='utf-8') as infile:
load_data_profile = json.load(infile)
except:
load_data_profile = {'profile': []} # default when file can't be read
load_data_profile['profile'].append({
'profile_name': profile_name_entry.get(),
'first_name': first_name_entry.get(),
'last_name': last_name_entry.get(),
'address': house_address_entry.get(),
'address2': house_address2_entry.get(),
'city': city_entry.get(),
'country': country_entry.get(),
'state': state_entry.get(),
'zip': zip_entry.get(),
'card_type': card_type_entry.get(),
'card_number': card_number_entry.get(),
'exp_month': card_exp_month_date_entry.get(),
'exp_year': card_exp_year_date_entry.get(),
'phone': phone_entry.get(),
'email': email_entry.get()
})
with open('profiles.txt', 'w', encoding='utf-8') as outfile:
json.dump(load_data_profile, outfile, indent=2)
答案 1 :(得分:0)
一种方法是采用Barmar的方法:读取,附加和写回。通常,这很好,但是扩展性不是很好,因为您必须解析整个文件,将整个内容加载到内存中,然后将整个内容写回到磁盘。当您的列表变大时,这是非常明显的。
如果您感到烦躁,可以以追加模式打开文件,并使用换行符(“ \ n”)分隔符以增量方式添加到文件中,然后在file.readlines()
上进行迭代以解析每个对象(甚至获得带有file.readlines()[40]
的特定商品,例如配置文件40)。
示例:
import json
def save_profile():
with open('profiles.txt', 'a') as file:
profile = {
"name": "John",
"age": 32
}
json.dump(profile, file)
file.write("\n")
def read_profiles():
with open('profiles.txt', 'r') as file:
profiles = file.readlines()
print(f"{len(profiles)} profiles")
for profile in profiles:
print(profile)
parsed = json.loads(profile)
save_profile()
read_profiles()
运行几次后的输出:
> python3 test.py
13 profiles
{"name": "John", "age": 32}
{"name": "John", "age": 32}
{"name": "John", "age": 32}
{"name": "John", "age": 32}
{"name": "John", "age": 32}
{"name": "John", "age": 32}
{"name": "John", "age": 32}
{"name": "John", "age": 32}
{"name": "John", "age": 32}
{"name": "John", "age": 32}
{"name": "John", "age": 32}
{"name": "John", "age": 32}
{"name": "John", "age": 32}