How to read from yaml file in Python

I am new to Python. I am trying to create a script to backup 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.

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

And here is the mistake.

 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?

+5
source share
3 answers

There are 2 problems:

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

Should work if the file is formatted as follows:

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

To back up the database , you can export it as a .sql file. If you use a specific interface, find Export .

Then for the parser Python yaml.

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

- thing key-value (sorry, did not find a better word for this). In a specific langage (e.g. PHP, I think), they are converted to objects. However, in python they are converted to dicts (the yaml parser does this, the JSON parser too).

 # access an object attribute my_obj.attribute = 'something cool' my_obj.attribute # something cool del my_obj.attribute my_obj.attribute # error # access a dict key value my_dict = {} my_dict['hello'] = 'world!' my_dict['hello'] # world! del my_dict['hello'] my_dict['hello'] # error 

So, this is a very quick presentation of dicts, but you should start (run help(dict) and / or look here you will not regret it)

In your case:

 config['DB_NAME'] # moodle_data 
+1
source

Try the following:

 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 
0
source

Source: https://habr.com/ru/post/1263654/


All Articles