python 递归 查找文件夹下文件

2019-06-13  本文已影响0人  牛奶大泡芙

用python自动搜索文件时,如果某文件夹下文件层级较深且文件操作频繁,可以用如下方法:

#coding:utf-8
import os
__metaclass__ = type


def get_file_path(file_path, file_target):
    """
        Search for files under the specified folder
        :string file_path: initial location of the search operation
        :string file_target: target file for the search operation
        :string: returns full absolute path of the target file or ''
    """
    for root, dirs, files in os.walk(file_path):
        for file in files:
            if file == file_target:
                return os.path.join(root, file)
    return ''


if __name__ == '__main__':
    common_get_file_path()

如果不同文件夹下可能有同名文件“abc.json”,可以利用上一层级的文件夹名称“father/abc.json”,作为输入

# coding=utf-8
import os
import copy


def search_folder(directory, file_target, dir_array):
    for x in directory:
        current_path = '/'.join(dir_array) + '/' + x
        if os.path.basename(x) == file_target:
            next_dir_array = copy.deepcopy(dir_array)
            next_dir_array.append(x)
            return next_dir_array
        elif os.path.isdir(current_path):
            os.chdir(current_path)
            next_dir_array = copy.deepcopy(dir_array)
            next_dir_array.append(x)
            inner_search_folder(os.listdir('.'), file_target, next_dir_array)
            os.chdir(os.path.abspath('..'))


def get_file_path(file_path, file_target):
    if '/' in file_target:
        folder = file_target.split('/')[0]
        file_name = file_target.split('/')[1]
        path = os.listdir(file_path)
        dir_array = []
        dir_array.append(file_path)
        r = inner_search_folder(path, folder, dir_array)
        path_result = '/'.join(r) + '/' + file_name
        return path_result
    else:
        for root, dirs, files in os.walk(file_path):
            for file in files:
                if file == file_target:
                    return os.path.join(root, file)
    return ''
上一篇下一篇

猜你喜欢

热点阅读