如何找到.asc文件5个文件夹深?

时间:2014-04-20 23:32:25

标签: python os.walk

我有几个.asc文件隐藏了5个文件夹深。例如:

main > Folder1a > Folder2a > Folder3a > Folder4a > myfile1.asc 
main > Folder1b > Folder2b > Folder3b > Folder4b > myfile2.asc 
main > Folder1c > Folder2c > Folder3c > Folder4c > myfile3.asc

我可以使用哪种方法获取myfile.asc文件夹中包含的main个文件列表?

2 个答案:

答案 0 :(得分:2)

f_walker = os.walk("/path/to/main")
f_generator = (os.path.join(cur,file) for cur,f,d in f_walker for file in f)
all_files = [file for file in f_generator if file.endswith(".asc")]

我认为......但是如果你知道他们只会有5级深度(从不4级而且从不6级......那么你可以优化一些)可能会变慢。

例如这样的事情可能会更快

import os
import glob

def go_deep(base_path,pattern,depth):
    if depth > 0:
        for fname in os.listdir(base_path):
            full_path = os.path.join(base_path,fname)
            if os.path.isdir(full_path):
                for fpath in go_deep(full_path,pattern,depth-1):
                    yield fpath
    else:
        for fname in glob.glob(pattern):
            yield os.path.join(base_path,fname)

print list(go_deep(".",pattern="*.asc",depth=5))

答案 1 :(得分:1)

这会奏效。使用点给出扩展名。目录不需要引号。与Joran的答案基本相同,来自用户的输入。这是为另一个项目做的......

import os

extension = input("enter extension:")
directory = input("enter directory to start in:")

for root, dirs, files in os.walk(directory):
    for fname in files:
        if fname.endswith(extension):
            full_fname = os.path.join(root, fname)
            print(full_fname)