def next_file(path):
'''
generator file in the path
'''
flist = os.listdir(path)
for fname in flist:
file_path = path + "/" + fname
if os.path.isfile(file_path):
yield file(file_path)
else:
yield next_file(file_path)
当文件是dir时,我想递归该函数。 但是当我接下来调用时,我会得到一个生成器。 有什么办法,我总能得到一个文件。
答案 0 :(得分:2)
要生成文件,请使用yield from next_file(file_path)
代替产生生成器对象的yield next_file(file_path)
。
在没有yield from
的较旧Python版本上,您可以在此处使用显式yield
循环:
for f in next_file(file_path):
yield f
答案 1 :(得分:1)
尝试
def next_file(path):
'''
generator file in the path
'''
flist = os.listdir(path)
for fname in flist:
file_path = path + "/" + fname
if os.path.isfile(file_path):
yield file(file_path)
else:
for f in next_file(file_path):
yield f
next_file
返回一个生成器,所以当你执行return next_file(file_path)
时,next_file
返回的生成器会被生成(而不是value),所以你需要迭代该生成器并yield
1}}所有元素一个接一个。