python - 使用字典将嵌套字典添加到已存在的 JSON 文件中
问题描述
我最近开始学习一些python。在完成所有 learnpython.org 教程后,我正在自己尝试一些东西(所以你知道我的知识水平)。
我想构建一个小脚本,让您构建一个 DnD 角色并将其保存在文件中。这个想法是使用 JSON(因为它包含在 learnpython 教程中)并按照以下方式放入字典:
data = { playerName ; {"Character Name" : characterName, "Character Class" : characterClass...ect.}}
我希望可以将新的 dics 添加到原始数据 dic 内的 JSON 文件中,因此字典是 playerName 的列表,其中包含字符 dics。
我不仅没有完全像这样得到它,而且在不使文件不可读的情况下添加以下字典也失败了。这是我的代码,因为它不是很长:
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 文件),请随时提出建议!
解决方案
我做了一点修改,我尝试读取文件以初始化数据 json,如果它失败我初始化数据。
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)
推荐阅读
- python - python - 一个指定网站上的 urllib2 错误 10060
- node.js - 为什么我重新启动计算机后sails.js会崩溃
- ms-access - 如何使用 MAX 或 DMAX 按天而不是按列获取结果
- excel - 如果单元格包含特定文本的多个实例,则提取单元格中找到的指定文本的前 3 个
- vim - vim:如何获取向上和向下搜索目录树的路径
- php - 无法通过php显示表格
- docker - 如何使用 Traefik 实现 fail2ban
- javascript - 如何使用 Firebase UI 访问 Firebase 中电子邮件帐户的 isNewUser?
- swift - 如何获取用户个人资料中的帖子?- 斯威夫特和火力基地
- vue.js - 如何突出显示 Vuetify 菜单中的选定项目?