|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Stubborn 于 2019-4-3 20:50 编辑
递归遍历:
- import os
- def search_file(start_dir, sp=""):
- os.chdir(start_dir)
- sp += " "
- for each_file in os.listdir(os.curdir):
- if os.path.isdir(each_file):
- print(sp+"目录:"+os.getcwd() + os.sep + each_file)
- search_file(each_file, sp)
- os.chdir(os.pardir)
- else:
- print(sp+"文件:"+os.getcwd() + os.sep + each_file)
- start_dir = r"C:\Users\Administrator\Desktop"
- search_file(start_dir)
复制代码
栈深度遍历(先进后出),遍历目录不懂👇提问
- import os
- def get_all_dir_deep(path):
- stack = []
- stack.append(path)
- while len(stack) !=0:
- dirpath = stack.pop()
- fileslist = os.listdir(dirpath)
- for filename in fileslist:
- fileabspath = os.path.join(dirpath,filename)
- if os.path.isdir(fileabspath):
- print("目录:",filename)
- stack.append(fileabspath)
- else:
- print("普通文件:",filename)
- path = "/Users/sstubborn/Desktop"
- get_all_dir_deep(path)
复制代码
队列广度遍历,先进先出
- import os
- import collections
- def get_all_dir_queue(path):
- queue = collections.deque() #建队列
- queue.append(path)
- #处理队列,当队列为空结束循环
- while len(queue) !=0:
- dirpath = queue.popleft()
- fileslist = os.listdir(dirpath)
- for filename in fileslist:
- fileabspath = os.path.join(dirpath,filename)
- if os.path.isdir(fileabspath):
- print("目录:",filename)
- queue.append(fileabspath)
- else:
- print("普通文件:",filename)
- path = "/Users/sstubborn/Desktop"
- get_all_dir_queue(path)
复制代码
|
|