简体   繁体   中英

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?

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']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM