脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python 遍历磁盘目录的三种方法

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

2021-09-30 00:48克莱汤普森 Python

这篇文章主要介绍了python 遍历磁盘目录的三种方法,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下

深度遍历

递归

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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是删除最后一位的元素,每次又遍历最后一位的文件夹,所以每一轮都会将次级目录下的文件夹遍历完成之后再遍历下个次级目录

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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)

广度遍历磁盘

用队列遍历磁盘

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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)

以上就是python 遍历磁盘目录的三种方法的详细内容,更多关于python 遍历磁盘目录的资料请关注服务器之家其它相关文章!

原文链接:https://blog.csdn.net/m0_49397655/article/details/115360002

延伸 · 阅读

精彩推荐