在Python中,如何查找目录下的所有文件,包括子目录中的文件? [英] In Python, how to find all the files under a directory, including the files in subdirectories?
问题描述
我已经尝试了这个代码,但不工作...可能是逻辑本身是错误的...
pre $ $ $ $ $ $ def fun(mydir):
lis = glob.glob(mydir)
length = len(lis)
l,i = 0,0
如果len(lis):
while(l + 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 $ c
这是微不足道的构造它:
$ p $ import $ $ b $ def recursive_file_gen(mydir)$:$ c>
用于文件中的文件:
yield os.path.join(r oot,file)
ETA : 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...
There is no built-in function, but using ETA: the
这篇关于在Python中,如何查找目录下的所有文件,包括子目录中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! os .walk
函数递归地遍历目录树; recursive_file_gen
函数是一个生成器(使用 yield
关键字来生成下一个文件)。要获得结果列表,请执行以下操作:
$ p $ list(recursive_file_gen(mydir))
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
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)
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))