如何使用生成器遍历文件系统? [英] How can I traverse a file system with a generator?

查看:100
本文介绍了如何使用生成器遍历文件系统?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个实用程序类,用于遍历目录中的所有文件,包括子目录和子子目录中的文件.我尝试使用发电机是因为发电机很酷.但是,我遇到了障碍.

I'm trying to create a utility class for traversing all the files in a directory, including those within subdirectories and sub-subdirectories. I tried to use a generator because generators are cool; however, I hit a snag.


def grab_files(directory):
    for name in os.listdir(directory):
        full_path = os.path.join(directory, name)
        if os.path.isdir(full_path):
            yield grab_files(full_path)
        elif os.path.isfile(full_path):
            yield full_path
        else:
            print('Unidentified name %s. It could be a symbolic link' % full_path)

当生成器到达目录时,它只是产生新生成器的内存位置;它没有给我目录的内容.

When the generator reaches a directory, it simply yields the memory location of the new generator; it doesn't give me the contents of the directory.

如果已经有一个简单的库函数以递归方式列出目录结构中的所有文件,请告诉我.我不打算复制库函数.

If there's already a simple library function to recursively list all the files in a directory structure, tell me about it. I don't intend to replicate a library function.

推荐答案

当您可以使用 os.walk

import os
for root, dirs, files in os.walk(path):
    for name in files:
        print os.path.join(root, name)

os.walk是一个生成器,它通过自上而下或自下而上地遍历目录树来产生目录树中的文件名

os.walk is a generator that yields the file names in a directory tree by walking the tree either top-down or bottom-up

这篇关于如何使用生成器遍历文件系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆