我如何从文本文件加载JSON数据,然后在python中添加到该数据上?

问题描述 投票:0回答:2

[我正在寻找一种通过程序保存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)

这只会将信息写入文件。由于我需要在此处重新键入所有内容,因此我遗漏了尝试过的部分。任何帮助都将受到赞赏!

python json
2个回答
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)

0
投票

一种方法是采用Barmar的方法:读取,附加和写回。通常,这很好,但是扩展性不是很好,因为您必须解析整个文件,将整个内容加载到内存中,然后将整个内容写回到磁盘。当您的列表变大时,这是非常明显的。

[如果您感到烦躁,可以在追加模式下打开文件,并使用换行符(“ \ n”)分隔符以增量方式添加到文件,然后在file.readlines()上进行迭代以解析每个对象(甚至获取一个特定的项目,例如配置文件#40,带有file.readlines()[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)

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}
© www.soinside.com 2019 - 2024. All rights reserved.