FarmerLi
4/13/2018 - 5:48 AM

Recursively traversing files under a directory, to process and mapping to an identical directory structure. 递归遍历文件,获取相同目录结构的目标路径.

Recursively traversing files under a directory, to process and mapping to an identical directory structure. 递归遍历文件,获取相同目录结构的目标路径.

import os
from os.path import splitext

def recurcively_process_files(src_dir, dst_dir, suffix = '.txt'):
    for lists in os.listdir(src_dir):
        src_path = os.path.join(src_dir, lists)
        dst_path = os.path.join(dst_dir, lists)
        if os.path.isfile(src_path):
            name = splitext(src_path)
            if name[1] == suffix:
                print src_path  # Procesing codes goes here.
        elif os.path.isdir(src_path):
            # If target dir is not exist, crate it!
            if not os.path.exists(dst_path):
                print "Creating " + dst_path
                os.makedirs(dst_path)
            recurcively_process_files(src_path, dst_path, suffix)