Python config file with YAML
Tom Withers
Posted on August 6, 2018
So I was googling for this myself about 4 weeks ago and couldn't find a straight answer, so I'm about to share an easy step by step solution with you.
First off I'm going to assume that you already know some python and have a project setup ready to go inside a venv.
First off lets import yaml,
import yaml
so now lets create a method called load_config
import yaml
def load_config(config_file):
As you can see we are also passing in config_file
, Next, we are going to open our config file as a stream using open
which is built into python.
import yaml
def load_config(config_file):
with open(config_file, 'r') as stream:
Using open, we can now open our config file and return a stream. So here we pass in our config_file
variable which we defined earlier, we also pass in another parameter which is a string of r
this basically tells open
which mode we want to open the file in. Now we can move on to loading our YAML file.
def load_config(config_file):
with open(config_file, 'r') as stream:
try:
return yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
As you can see above, we now load our YAML file using safe_load
. It's extremely important to use safe_load
here, safe_load
only resolves basic YAML tags, whereas load
does not. This is also wrapped in a try except
block so we can handle any errors.
All that's left to do now is call our method to load the file, make sure you pass in the path to your config.yml file here.
config = load_config('config.yml')
This is my first ever blog post any feedback would be greatly appreciated! :)
Posted on August 6, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.