在Python中,如何查找目录下的所有文件,包括子目录中的文件? [英] In Python, how to find all the files under a directory, including the files in subdirectories?

查看:1650
本文介绍了在Python中,如何查找目录下的所有文件,包括子目录中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有内置的函数来查找特定目录下的所有文件,包括子目录下的文件?
我已经尝试了这个代码,但不工作...可能是逻辑本身是错误的...

pre $ $ $ $ $ $ def fun(mydir):
lis = glob.glob(mydir)
length = len(lis)
l,i = 0,0
如果len(lis):
while(l + i if os.path.isfile(lis [i]):
final.append(lis [i])
lis.pop(i )
l = l + 1
i = i + 1
else:
i = i + 1
print final
fun(lis)
else :
print final


解决方案

在功能,但使用 os.walk
$ p $ import $ $ b $ def recursive_file_gen(mydir)$:$ c>
这是微不足道的构造它:

b $ b用于root,dirs,os.walk(mydir)中的文件:
用于文件中的文件:
yield os.path.join(r oot,file)

ETA : os .walk 函数递归地遍历目录树; recursive_file_gen 函数是一个生成器(使用 yield 关键字来生成下一个文件)。要获得结果列表,请执行以下操作:

$ p $ list(recursive_file_gen(mydir))


Is there any built in functions to find all the files under a particular directory including files under subdirectories ? I have tried this code, but not working...may be the logic itself is wrong...

def fun(mydir):
    lis=glob.glob(mydir)
    length=len(lis)
    l,i=0,0
    if len(lis):
        while(l+i<length):
            if os.path.isfile(lis[i]):
                final.append(lis[i])
                lis.pop(i)
                l=l+1
                i=i+1
            else:
                i=i+1
            print final
        fun(lis)
    else:
        print final

解决方案

There is no built-in function, but using os.walk it's trivial to construct it:

import os
def recursive_file_gen(mydir):
    for root, dirs, files in os.walk(mydir):
        for file in files:
            yield os.path.join(root, file)

ETA: the os.walk function walks directory tree recursively; the recursive_file_gen function is a generator (uses yield keyword to produce next file). To get the resulting list do:

list(recursive_file_gen(mydir))

这篇关于在Python中,如何查找目录下的所有文件,包括子目录中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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