在python中加载带有通配符的yaml文件

在python中加载带有通配符的yaml文件,python,python-2.7,pyyaml,Python,Python 2.7,Pyyaml,我想打开文件夹中的所有*.yaml文件并用PyYaml加载它们。每个文件包含一个yaml文档。 我最近的代码片段: stream = open("conf.d/*.yaml", 'r') config = yaml.load_all(stream) 这会失败,因为yaml.open显然无法使用通配符: stream = open("conf.d/*.yaml", 'r') IOError: [Errno 2] No such file or directory: 'conf.d/*.yaml'

我想打开文件夹中的所有*.yaml文件并用PyYaml加载它们。每个文件包含一个yaml文档。 我最近的代码片段:

stream = open("conf.d/*.yaml", 'r')
config = yaml.load_all(stream)
这会失败,因为yaml.open显然无法使用通配符:

stream = open("conf.d/*.yaml", 'r')
IOError: [Errno 2] No such file or directory: 'conf.d/*.yaml'

如何正确地存档此目标?

在Python 2.5+中,可以使用
glob
模块将通配符扩展为文件名列表

>>> import glob
>>> a = glob.glob("*.yaml")
>>> print a
['test1.yaml', 'test2.yaml', 'test3.yaml']
然后,您可以将其提供给迭代器,如
map()
,以生成PyYAML配置生成器列表

>>> import yaml
>>> import glob
>>> configs = map(lambda x: yaml.load_all(open(x)), glob.glob("*.yaml"))
>>> print configs
[<generator object load_all at 0x1078bfe10>, <generator object load_all at 0x1078bfd20>, <generator object load_all at 0x1078bfb90>]
>>> for config in configs:
...     for item in config:
...         print item
... 
{'date': datetime.date(2015, 2, 27), 'customer': {'given': 'Gordon', 'family': 'Jeff'}, 'location': 'Target'}
{'date': datetime.date(2015, 2, 25), 'customer': {'given': 'Earnhardt', 'family': 'Dale'}, 'location': 'Walmart'}
{'date': datetime.date(2015, 2, 23), 'customer': {'given': 'Petty', 'family': 'Richard'}, 'location': 'Target'}
>>导入yaml
>>>导入glob
>>>configs=map(lambda x:yaml.load_all(open(x)),glob.glob(“*.yaml”))
>>>打印配置
[, ]
>>>对于配置中的配置:
...     对于配置中的项目:
...         打印项目
... 
{'date':datetime.date(2015,2,27),'customer':{'given':'Gordon','family':'Jeff'},'location':'Target'}
{'date':datetime.date(2015年2月25日),'customer':{'given':'Earnhardt','family':'Dale'},'location':'Walmart'}
{'date':datetime.date(2015,2,23),'customer':{'given':'Petty','family':'Richard'},'location':'Target'}

这解决了通配符本身的问题,但open需要一个字符串或流作为输入。@Dakkar更新为迭代文件名并生成配置。请记住,
yaml.load\u all
只接受一个流或字符串。如果需要单个组合配置,可以尝试读取
*.yaml
文件的内容,并将其连接到单个字符串对象中,以馈送到
加载\u all
。这确实会产生覆盖重复YAML键的不良效果。