网络编程
位置:首页>> 网络编程>> Python编程>> python 遍历磁盘目录的三种方法

python 遍历磁盘目录的三种方法

作者:克莱汤普森  发布时间:2021-10-15 06:36:14 

标签:python,遍历,磁盘,目录
目录
  • 深度遍历

    • 递归

    • 用栈来遍历磁盘

  • 广度遍历磁盘

    • 用队列遍历磁盘

深度遍历

递归


import os

def get_files(path):
 # 判断路径是否存在,如果不存在,函数直接结束
 if not os.path.exists(path):
   print('路径不存在')
   return
 # 判断路径是否为文件夹
 if not os.path.isdir(path):
   print('路径是一个文件')
   return
 # 这时候,路径是一个文件夹
 # 获取文件夹中文件或文件夹的名称
 file_list = os.listdir(path)
 # 遍历文件夹
 for filename in file_list:
   # 拼接路径,获取每个次级目录下的文件路径
   subpath = os.path.join(path,filename)
   if os.path.isfile(subpath):
     if os.path.splitext(subpath)[1] == '.py':
       print('python文件:{}'.format(subpath))
   else:
     # 如果filename是文件夹,则调用函数继续遍历
     get_files(subpath)

用栈来遍历磁盘

栈的特点:先进后厨,后进先出
原理:path第一次被pop删除后返回path,遍历目录下的文件,如果遇到文件夹追加到列表中,pop是删除最后一位的元素,每次又遍历最后一位的文件夹,所以每一轮都会将次级目录下的文件夹遍历完成之后再遍历下个次级目录


import os

def get_files(path):
 # 判断路径是否存在
 if not os.path.exists(path):
   print('路径不存在')
   return
 if not os.path.isdir(path):
   print('路径是一个文件夹')
   return
 # 创建一个列表作为栈
 stack = [path]
 # 取出栈中的元素
 while len(stack) != 0:
   path = stack.pop()
   file_list = os.listdir(path)
   for filename in file_list:
     subpath = os.path.join(path,filename)
     if os.path.isfile(subpath):
       print('python文件:{}'.format(subpath))
     else:
       stack.append(subpath)

广度遍历磁盘

用队列遍历磁盘


import os
import collections

def get_py_file(path):
 # 判断路径是否存在
 if not os.path.exists(path):
   print('路径不存在')
   return
   # 判断路径是否是文件夹
 if os.path.isfile(path):
   print('路径是文件')
   return
   # path是一个文件夹

# 定义一个空对列
 queue = collections.deque()
 queue.append(path)
 while len(queue) != 0:
   # 从队列中获取第一个元素
   path = queue.popleft()
   # 获取目录下的所有内容
   filelist = os.listdir(path)
   # 遍历
   for filename in filelist:
     # 拼接
     filepath = os.path.join(path, filename)
     if os.path.isfile(filepath):
       if os.path.splitext(filepath)[1] == '.py':
         print(filepath)
     else:
       queue.append(filepath)

来源:https://blog.csdn.net/m0_49397655/article/details/115360002

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com