1、递归调用目录
import os
def get_all_dir_re(path, sp = ''):
file_list = os.listdir(path)
sp += ' '
for fileName in file_list:
file_abs_path = os.path.join(path, fileName)
if os.path.isdir(file_abs_path):
print(sp + '目录:' + fileName)
get_all_dir_re(file_abs_path, sp)
else:
print(sp + '普通文件:' + fileName)
get_all_dir_re(r'D:\BaiduNetdiskDownload')
2、栈模拟递归遍历目录(深度遍历)
import os
def get_all_dir_de(path, sp = ''):
stack = []
stack.append(path)
while len(stack) != 0:
dirpath = stack.pop()
files_list = os.listdir(dirpath)
for file_name in files_list:
file_abs_name = os.path.join(dirpath, file_name)
if os.path.isdir(file_abs_name):
print(sp + '目录:' + file_name)
stack.append(file_abs_name)
else:
print(sp + '普通文件:' + file_name)
get_all_dir_de(r'D:\BaiduNetdiskDownload')
3、队列模拟递归遍历目录(广度遍历)
import os
import collections
def get_all_dir_qu(path):
queue = collections.deque()
queue.append(path)
while len(queue) != 0:
dirpath = queue.pop()
files_list = os.listdir(dirpath)
for file_name in files_list:
file_abs_name = os.path.join(dirpath, file_name)
if os.path.isdir(file_abs_name):
print('目录:' + file_name)
queue.append(file_abs_name)
else:
print('普通文件:' + file_name)
get_all_dir_qu(r'D:\BaiduNetdiskDownload')