python递归遍历目录和子目录下的所有文件,并将文件目录存入列表
本文编写了一个函数,实现递归查找目标目录
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))
运行结果(参考):
[’./raw_data/drawings/urls_drawings.txt’, ‘./raw_data/hentai/urls_hentai.txt’, ‘./raw_data/neutral/urls_neutral.txt’, ‘./raw_data/porn/urls_porn.txt’, ‘./raw_data/sexy/urls_sexy.txt’]
[Finished in 0.4s]