Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading YAML file with Python results in AttributeError

Tags:

python

yaml

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'

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

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

And this is an error that comes up:

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?

like image 598
Yerlan Yeszhanov Avatar asked Feb 01 '17 08:02

Yerlan Yeszhanov


People also ask

How do I read a YAML file in Python?

We can read the YAML file using the PyYAML module's yaml. load() function. This function parse and converts a YAML object to a Python dictionary ( dict object). This process is known as Deserializing YAML into a Python.

Is PyYAML same as YAML?

YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for the Python programming language.

What is PyYAML used for?

PyYAML allows you to construct a Python object of any type. Even instances of Python classes can be constructed using the !! python/object tag. Note that the ability to construct an arbitrary Python object may be dangerous if you receive a YAML document from an untrusted source such as the Internet.

Does YAML come with Python?

This statement is mostly true, as the standard library and the external modules cover a broad spectrum of programming needs. However, Python lacks built-in support for the YAML data format, commonly used for configuration and serialization, despite clear similarities between the two languages.


1 Answers

There are 2 issues:

  • As others have said, yaml.load() loads associative arrays as mappings, so you need to use config['DB_NAME'].
  • The syntax in your config file is not correct: in YAML, keys are separated from values by a colon+space.

Should work if the file is formatted like this:

DB_HOST: 'localhost'
DB_USER: 'root'
DB_USER_PASSWORD: 'P@$$w0rd'
DB_NAME: 'moodle_data'
BACKUP_PATH: '/var/lib/mysql/moodle_data'
like image 150
Roel Schroeven Avatar answered Oct 06 '22 19:10

Roel Schroeven