Search code examples
pythonpython-2.7yamlpyyaml

How do I read/parse all yaml files in a directory?


Well, I am trying to read a collection of utf-8 yaml files in a directory with python 2.7 and pyyaml. I tried to use os.listdir(os.getcwd()), but it actually returns a list of files and I need to read the files and exhibit the content (key, value). The directory only has yaml files and pyyaml library is already installed.

All the content of the yaml files are similar to this:

fruits:
 - bananas
 - apples
 - grapes

Can anyone help me?


Solution

  • You can try this:

    content of demo_file1.yaml:

    fruits:
      - bananas
      - apples
      - grapes
    

    content of demo_file2.yaml:

    veg:
      - cauli
      - lady finger
      - tomato
    

    Code:

    import yaml
    import glob
    
    files = glob.glob("/path/to/directory/*.yaml") # list of all .yaml files in a directory 
    
    def read_yaml_file(filename):
        with open(filename, 'r') as stream:
            try:
                print(yaml.safe_load(stream))
            except yaml.YAMLError as exc:
                print(exc)
    
    for file in files:
        read_yaml_file(file)
    

    output:

    {'fruits': ['bananas', 'apples', 'grapes']}
    {'veg': ['cauli', 'lady finger', 'tomato']}