Python中yield使用方式

利用yield的函数遍历目录,实现按顺序处理文件,我在这里处理的是xml,可以根据需要改变!

def xml1(path):
    for i in range(0, len(os.listdir(path))):
        yield os.path.join(path, str(i) + '.xml')


def xml2(path):
    for i in range(1, len(os.listdir(path))):
        yield os.path.join(path, str(i) + '.xml')


if __name__ == "__main__":
    # 传入xml的路径
    path = ''
    path1 = xml1(path)
    path2 = xml2(path)
    i = 0
    while True:
        if i >= len(os.listdir(path)) - 1:
            break
        print(next(path1), next(path2))
        i += 1

你可能感兴趣的:(Python脚本)