Yerlan Yeszhanov
Yerlan Yeszhanov

Reputation: 2439

Reading YAML file with Python results in AttributeError

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?

Upvotes: 12

Views: 28396

Answers (3)

Roel Schroeven
Roel Schroeven

Reputation: 1822

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'

Upvotes: 12

Mathieu Paturel
Mathieu Paturel

Reputation: 4500

To backup your data base, you should be able to export it as a .sql file. If you're using a specific interface, look for Export.

Then, for Python's yaml parser.

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

is a key-value thing (sorry, didn't find a better word for that one). In certain langage (such as PHP I think), they are converted to objects. In python though, they are converted to dicts (yaml parser does it, JSON parser too).

# access an object's attribute
my_obj.attribute = 'something cool'
my_obj.attribute # something cool
del my_obj.attribute
my_obj.attribute # error

# access a dict's key's value
my_dict = {}
my_dict['hello'] = 'world!'
my_dict['hello'] # world!
del my_dict['hello']
my_dict['hello'] # error

So, that's a really quick presentation of dicts, but that should you get you going (run help(dict), and/or have a look here you won't regret it)

In your case:

config['DB_NAME'] # moodle_data

Upvotes: 3

Shivkumar kondi
Shivkumar kondi

Reputation: 6762

Try this:

import yaml
with open('config.yaml', 'r') as f:
    doc = yaml.load(f)

To access "DB_NAME" you can use:

txt = doc["DB_NAME"]
print txt

Upvotes: 1

Related Questions