Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Read in YAML or JSON file using Python

The following code will read in a YAML file and store it in a dictionary. The dictionary content is then printed to the console.

config.yaml

test: value
nested:
  test: nestedValue

script.py

import json
import yaml

config = {}
with open("config.yml", "r") as stream:
    config = yaml.safe_load(stream)
    # config = json.load(stream) to load JSON data

print(config['test'])
print(config['nested']['test'])
print(json.dumps(config, indent=4))

console output

value
nestedValue
{
    "test": "value",
    "nested": {
        "test": "nestedValue"
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.