使用字典将嵌套字典添加到已存在的JSON文件中

2024-10-04 05:26:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近开始学习一些python。 在完成所有learnpython.org教程之后,我正在自己尝试一些东西(这样你就知道我的知识水平了)

我想建立一个小脚本,让你建立一个DnD字符,并保存在一个文件中。我们的想法是使用JSON(因为它包含在learnpython教程中),并将以下内容放入字典中:

data = { playerName ; {"Character Name" : characterName, "Character Class" : characterClass...ect.}}

我希望有可能在原始数据dic中的JSON文件中添加新的dic,因此字典是一个包含字符dic的playerName列表

我不仅没有完全像这样得到它,而且在添加以下字典而不使文件不可读方面也失败了。这是我的代码,因为它不是很长:

import json


def dataCollection():
    print("Please write your character name:")
    characterName = input()
    print("%s, a good name! \nNow tell me your race:" % characterName)
    characterRace = input()
    print("And what about the class?")
    characterClass = input()
    print("Ok so we have; \nName = %s \nRace = %s \nClass = %s \nPlease tell me the player name now:" % (characterName, characterRace, characterClass))
    playerName = input()
    print("Nice to meet you %s. \nI will now save your choices..." % playerName)
    localData = { playerName : 
                 {"Character Name" : characterName,
                  "Character Class" : characterClass,
                  "Character Race" : characterRace}}

    with open("%s_data_file.json" % playerName, "a") as write_file:
        json.dump(localData, write_file)
        
    


dataCollection()

with open("data_file.json", "r") as read_file:
    data = json.load(read_file)
# different .json name here since I'm trying around with different files

print(data)

编辑:也可能JSON不是我的想法中“正确”的东西。如果您对存储该信息有任何其他想法(除了直接的txt文件),请随时提出建议


Tags: 文件namejsoninputdata字典filewrite
2条回答

我认为你对辞典的看法可能并不完全是这样。 字典是一种可以保存许多键值对的数据结构

在这里,字典的键是玩家的名字,值是保存角色名字、职业和种族的字典

因此,无法追加包含字典的json文件,因为json文件只能包含1个json对象

{ 'playerName': {...character\'s attributes...}}

如果要打开该文件并附加一个json对象(就像在dataCollection末尾所做的那样),那么文件将如下所示

{ 'playerName':
    {...characters attributes...}
}
{ 'playerName2':
    {...characters attributes...}
}

读取文件时json将在找到的第一个json对象结束时停止。所以它不会加载第二个字典

如果要在json文件中向字典添加内容,则需要加载json文件以访问字典,然后添加新的键值对,然后转储此新字典。这将生成以下json文件:

{ 'playerName':
    {...characters attributes...},
  'playerName2':
    {...characters attributes...}
}

我希望有点清楚

我做了一些修改,我尝试读取init-the-data-json的文件,如果失败,我将init-the-data

import json


def createPlayer():
    print("Please write your character name : ")
    characterName = input()
    print("%s, a good name! \nNow tell me your race : " % characterName)
    characterRace = input()
    print("Nice to meet you %s. \nI will now save your choices..." % characterName)

    try :
        with open('data_file.json') as json_file:
            data = json.load(json_file)
    except :
        data = {}
        data['player'] = []

    data['player'].append({
    'name': characterName,
    'race': characterRace,
    })

    with open("data_file.json", "w+") as write_file:
        json.dump(data, write_file)

createPlayer()

with open("data_file.json", "r") as read_file:
    data = json.load(read_file)

print(data)

相关问题 更多 >