logo头像
Snippet 博客主题

Python3 - 遍历目录

通过三种方式遍历目录 – 递归、栈、队列

一、递归遍历目录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import os # 导入os模块
def getAllDir(path):
# os.listdir 返回指定文件夹目录(列表形式)
fileAll = os.listdir(path) # 获取path目录下的所有文件及子目录
for fileName in fileAll: # 遍历获取path目录下的所有文件及子目录 fileName即为目录名或文件名
# os.path.join 全路径的拼接
filePath = os.path.join(path, fileName) # 将path目录与目录名或文件名拼接起来, 以便下一步判断
# os.path.isdir 判断是否是目录
if os.path.isdir(filePath):
print('文件夹:' + fileName) # 如果为目录, 打印输出目录
getAllDir(filePath, str) # 递归getAllDir()方法 直到目录下面的文件全部遍历出来
else:
print('文件: ' + fileName) # 如果为文件, 打印输出文件
getAllDir(path)

二、使用栈模拟递归遍历目录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import os # 导入os模块
def getALLDir(path):
list1 = []
list1.append(path)
while len(list1) != 0:
# 开始从列表中取数据
dirPath = list1.pop()
# 得到文件下边的所有文件路径
filesAll = os.listdir(dirPath)
for filename in filesAll:
# 路径拼接全路径
filePath = os.path.join(dirPath, filename)
if os.path.isdir(filePath):
# 是目录
list1.append(filePath)
else:
# 是文件
print('文件' + filename)

三. 使用队列模拟递归遍历目录

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
import os # 导入os模块
import collections # 导入collections模块

def getAllDir(path):
# 创建列表
# 使用collections.deque方法可以创建一个两端都可以操作的列表,也就是说我们可以在两端进行添加和删除
que = collections.deque()
que.append(path)

while len(que) != 0:
# 得到文件路径
dirPath = que.popleft()

# 获取该路径下边的文件和文件夹
filesPath = os.listdir(dirPath)

for filename in filesPath:
# 拼接全路径
filePath = os.path.join(dirPath, filename)

if os.path.isdir(filePath):
# 是目录
que.append(filePath)
else:
# 是文件
print('文件' + filename)

评论系统未开启,无法评论!