【发布时间】:2019-06-04 09:59:25
【问题描述】:
所以我有一个函数循环遍历目录中的所有文件名,打开 yaml 文件并获取两个属性,即数据库名称和集合名称。当我在函数中使用print 语句而不是return 时,这将输出所有文件名。但是,当使用return 语句时,它只会返回一个值。我真的不知道为什么我会得到这个输出并且已经尝试了很多次来弄清楚它为什么这样做。我的功能如下:
def return_yml_file_names():
"""return file names from the yaml directory"""
collections = os.listdir('yaml/')
collections.remove('export_config.yaml')
for file in collections :
with open('yaml/' + file, 'r') as f:
doc = yaml.load(f)
collection_name = doc["config"]["collection"]+".json"
return collection_name
print(return_yml_file_names())
【问题讨论】:
-
将每个值添加到列表中,然后在循环完成后返回列表。
-
我已经尝试过了,但是这样做时它返回 None @ekhumoro
-
那是因为你实际上并没有返回列表。
-
或使用
yield代替return
标签: python python-2.7 return return-value