今天看啥  ›  专栏  ›  蒸饺与白茶

[Python与数据分析]-21python递归遍历目录和子目录下的所有文件,并将文件目录存入列表

蒸饺与白茶  · 简书  ·  · 2021-05-17 11:03

本文编写了一个函数,实现递归查找目标目录 path 和目标目录下的多层子目录下的所有文件,并将所有文件的 path 存放于一个list列表中。

import os

def get_file(root_path,all_files=[]):
    '''
    递归函数,遍历该文档目录和子目录下的所有文件,获取其path
    '''
    files = os.listdir(root_path)
    for file in files:
        if not os.path.isdir(root_path + '/' + file):   # not a dir
            all_files.append(root_path + '/' + file)
        else:  # is a dir
            get_file((root_path+'/'+file),all_files)
    return all_files

# example
path = './raw_data'
print(get_file(path))



原文地址:访问原文地址
快照地址: 访问文章快照