分离配置文件并拆分密钥收集在自己的fi中

2024-09-24 22:17:45 发布

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

一个新的更新,使这个插件,所以所有的“任务”必须在一个单独的文件。因为有超过100个,我不想手动操作。旧文件(“config.yml”)看起来像这样:“quests.{questname}.{attributes}.{attributes}作为属于当前任务的每个键。新文件应以{questname}作为名称,并在其中包含属性。所有文件都应该这样做

config.yml(旧文件)

quests:
  farmingquest41:
    tasks:
      mining:
        type: "blockbreakcertain"
        amount: 100
        block: 39
    display:
      name: "&a&nFarming Quest:&r &e#41"
      lore-normal:
      - "&7This quest will require you to farm certain"
      - "&7resources before receiving the reward."
      - "&r"
      - "&6* &eObjective:&r &7Mine 100 brown mushrooms."
      - "&6* &eProgress:&r &7{mining:progress}/100 brown mushrooms."
      - "&6* &eReward:&r &a1,500 experience"
      - "&r"
      lore-started:
      - "&aYou have started this quest."
      type: "BROWN_MUSHROOM"
    rewards:
     - "xp give {player} 1500"
    options:
      category: "farming"
      requires:
       - ""
      repeatable: false
      cooldown:
        enabled: true
        time: 2880

我所做的是循环遍历数据中的每个“任务”,这将创建一个位于“Quests/Quests/{questname}.yml”中的带有任务属性的“outfile”。不过,我似乎可以让它工作,得到一个“字符串索引必须是整数”

import yaml

input = "Quests/config.yml"

def splitfile():
    try:
        with open(input, "r") as stream:
            data = yaml.load(stream)
            for quest in data:  
                outfile = open("Quests/quests/" + quest['quests'] + ".yml", "x")
                yaml.dump([quest], outfile)
    except yaml.YAMLError as out:
        print(out)

splitfile()

循环遍历数据中的每个“任务”,这将创建一个位于“Quests/Quests/{questname}.yml”中的带有任务属性的“outfile”


Tags: 文件configyaml属性ymltypeoutfileattributes
1条回答
网友
1楼 · 发布于 2024-09-24 22:17:45

错误来自quest['quests']。您的数据是一个字典,其中有一个条目名为quests

for quest in data:
  print(quest) # will just print "quests"

要在yaml中正确迭代,您需要:

  1. 使用data["quests"]获取任务字典
  2. 对于任务字典中的每个条目,使用条目键作为文件名并将条目值转储到文件中

以下是您的脚本的修补版本:

def splitfile():
    try:
        with open(input, "r") as stream:
            data = yaml.load(stream)
            quests = data['quests'] # get the quests dictionary
            for name, quest in quests.items():  
                # .items() returns (key, value), 
                # here name and quest attributes
                outfile = open("Quests/quests/" + name + ".yml", "x")
                yaml.dump(quest, outfile)
    except yaml.YAMLError as out:
        print(out)

splitfile()

相关问题 更多 >