python - 使用 Python 读取 YAML 文件导致 AttributeError

标签 python yaml

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

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

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

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'

有谁知道我在哪里犯了错误吗?

最佳答案

有两个问题:

  • 正如其他人所说,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 - 使用 Python 读取 YAML 文件导致 AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41974628/

相关文章:

python - 打开文件对象的大小

shell - 如何将yaml文件格式化为csv格式?

android - CI Android项目-gradlew没有此类文件

symfony - 从 Controller 和/或 Twig 模板访问服务

python - 通过整数位置和列标签获取标量(混合索引)

带有网络存档的 Python 报纸(回归机器)

yaml - 出现错误 : Circular dependency between resources

powershell - 在 Yaml 管道中修复 PowerShell

python队列获取大小,使用qsize()还是len()?

python PPTX : How to Update or Replace a Chart Series?