我最近开始学习一些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文件),请随时提出建议
我认为你对辞典的看法可能并不完全是这样。 字典是一种可以保存许多键值对的数据结构
在这里,字典的键是玩家的名字,值是保存角色名字、职业和种族的字典
因此,无法追加包含字典的json文件,因为json文件只能包含1个json对象
如果要打开该文件并附加一个json对象(就像在
dataCollection
末尾所做的那样),那么文件将如下所示读取文件时
json
将在找到的第一个json对象结束时停止。所以它不会加载第二个字典如果要在json文件中向字典添加内容,则需要加载json文件以访问字典,然后添加新的键值对,然后转储此新字典。这将生成以下json文件:
我希望有点清楚
我做了一些修改,我尝试读取init-the-data-json的文件,如果失败,我将init-the-data
相关问题 更多 >
编程相关推荐