Discuss / Python / 三种方法

三种方法

Topic source

1,glob

import glob
def searchFlie(path='.', format = '.py'):
    for i in glob.glob(path + '/**/*' + format, recursive=True):    #使用**及recursive来遍历所有子目录
        print(i)

2,os.walk

import os
def searchFlie(path='.', format='.py'):
    files = []
    for r, d, f in os.walk(path):    
        for file in f:
            if format in file:
                files.append(os.path.join(r, file))
    return files

3,递归

def searchFlie(path='.', format = '.py'):
    for file in os.listdir(path):
        childpath = os.path.join(path, file)
        if os.path.isdir(childpath):
            searchFlie(path=childpath, format=format)
        else:
            if os.path.splitext(file)[1] == format:
                print(childpath)

在路上Ce

#2 Created at ... [Delete] [Delete and Lock User]

很好,必须给赞一个

在路上Ce

#3 Created at ... [Delete] [Delete and Lock User]
def search_file_using_stack(path = '.', format = '.py'):
    stack = []
    stack.append(path)
    file_list = []
    while stack:
        file_dir = stack.pop()
        for file in os.listdir(file_dir):
            childpath = os.path.join(file_dir, file)
            if os.path.isdir(childpath):
                stack.append(childpath)
            else:
                if os.path.splitext(childpath)[1] == format:
                    file_list.append(childpath)

    return file_list

补充一个递归的扩展:使用栈将递归转换成迭代。也可以用队列(collections包里的deque)来辅助实现。结果是一样的,区别是目录的处理顺序。队列是广度优先搜索,/a/b/c /a/d这种目录结构的话,会先搜索/a/b和/a/d,按层来。用栈就是深度优先搜索,会先/a/b/c,搜索完成后再查/a/d。

浪过扬帆

#4 Created at ... [Delete] [Delete and Lock User]

pathlib模块,谁用谁知道


  • 1

Reply