簡體   English   中英

如何從文本文件加載 JSON 數據,然后在 python 中添加到該數據中?

[英]How can i load JSON data from a text file and then add onto that data in python?

我正在尋找一種方法來用我的程序保存我的 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)

這只會將信息寫入文件。 我省略了我嘗試過的部分,因為我需要在這里重新輸入所有內容。 任何和所有的幫助表示贊賞!

首先使用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)

一種方法是采用 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)
            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}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM