使用 Python 读取 YAML 文件导致 AttributeError [英] Reading YAML file with Python results in AttributeError

查看:40
本文介绍了使用 Python 读取 YAML 文件导致 AttributeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个脚本来备份 MySQL 数据库.我有一个 config.yml 文件:

I'm trying to make a script to back up a MySQL database. I have a config.yml file:

DB_HOST :'localhost'
DB_USER : 'root'
DB_USER_PASSWORD:'P@$$w0rd'
DB_NAME : 'moodle_data'
BACKUP_PATH : '/var/lib/mysql/moodle_data'

现在我需要阅读这个文件.到目前为止,我的 Python 代码:

Now I need to read this file. My Python code so far:

import yaml
config = yaml.load(open('config.yml'))
print(config.DB_NAME)

这是一个出现的错误:

file "conf.py", line 4, in <module>
print(config.DB_NAME)
AttributeError: 'str' object has no attribute 'DB_NAME'

有人知道我哪里出错了吗?

Does anyone have an idea where I made a mistake?

推荐答案

有2个问题:

  • 正如其他人所说,yaml.load() 加载关联数组作为映射,因此您需要使用 config['DB_NAME'].
  • 您的配置文件中的语法不正确:在 YAML 中,键与值之间用冒号+空格分隔.

如果文件格式如下:

DB_HOST: 'localhost'
DB_USER: 'root'
DB_USER_PASSWORD: 'P@$$w0rd'
DB_NAME: 'moodle_data'
BACKUP_PATH: '/var/lib/mysql/moodle_data'

这篇关于使用 Python 读取 YAML 文件导致 AttributeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆