如何从Python文件访问YAML数据?

2024-06-28 11:34:43 发布

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

我目前正在使用Discord.py制作一个Discord Bot,并配置了YAML。下面是一个简短的YAML配置,取自我的“hartexConfig.YAML”文件:

general:
    hartexToken = 'the bot token'

然后我尝试在hartex.py文件中访问它:

class Hartex(discord.Client):
    def __init__(self, *args, **kwargs):
        super().__init__()

    hartexTokenValue = open('HarTex/hartexConfig.yaml', 'r')

    hartexToken = hartexTokenValue['general']['hartexToken']

    yamlStream = True

我怎么能这样做,还是我完全错了

PS我想访问一段特定的数据,就像在本例中,我只想从YAML文件中读取hartexToken


Tags: 文件thepytokenyamlinitbotclass
2条回答
import yaml

class Hartex(discord.Client):
    def __init__(self, *args, **kwargs):
        super().__init__()

    with open('HarTex/hartexConfig.yaml', 'r') as hartexConfig:
        # this is the part where your config is actually parsed
        hartexTokenValue = yaml.safe_load(hartexConfig) 

    hartexToken = hartexTokenValue['general']['hartexToken']

你确定yaml是正确的吗?{}应该是一个{};目前,键将是general,其值为hartexToken = 'the bot token'

(您需要安装pyyaml)

pip install pyyaml


>>> import yaml
>>> with open('demo.yaml','r') as f:
...    datamap = yaml.safe_load(f)
... 
>>> datamap
{'general': "hartexToken = 'the bot token'"}

如果yaml确实如您所说,那么您当然可以split获取“bot令牌”的值

>>> datamap['general'].split('=')[1]
" 'the bot token'"

相关问题 更多 >