python遍历目录

这里介绍两种方法

深度优先

即先遍历当前目录下的第一个目录里面的第一个目录,以此类推,然后再逐层向上遍历。
代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
import os
def gci(filepath):
#遍历filepath下所有文件,包括子目录
files = os.listdir(filepath)
for fi in files:
fi_d = os.path.join(filepath,fi)
if os.path.isdir(fi_d):
print(os.path.join(filepath, fi_d))
gci(fi_d)
else:
print(os.path.join(filepath,fi_d))#递归遍历/root目录下所有文件
gci('f:\\test')

运行结果:

1
2
3
4
5
6
7
8
9
10
11
12
f:/test/a
f:/test/a/a1
f:/test/a/a2
f:/test/a/a3
f:/test/b
f:/test/b/b1
f:/test/b/b2
f:/test/b/b3
f:/test/c
f:/test/c/c1
f:/test/c/c2
f:/test/c/c3

广度优先

是先把当前目录下的所有文件文件夹打印出来,再分别进每一个文件夹打印相应的文件文件夹,再一次类推,逐层往下。
代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import os.path
rootdir = 'f:\\test' # 指明被遍历的文件夹
def gci(rootdir):
for parent,dirnames,filenames in os.walk(rootdir): #三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字
for dirname in dirnames: #输出文件夹信息
#print("parent is:" + parent)
#print("dirname is:" + dirname)
#print("the full name of the file is:" + os.path.join(parent, dirname)) # 输出文件夹路径信息
print(os.path.join(parent, dirname)) # 输出文件夹路径信息

for filename in filenames: # 输出文件信息
#print("parent is:" + parent)
#print("filename is:" + filename)
#print("the full name of the file is:" + os.path.join(parent, filename)) # 输出文件路径信息
print(os.path.join(parent, filename)) # 输出文件路径信息
gci(rootdir)

运行结果:

1
2
3
4
5
6
7
8
9
10
11
12
f:/test/a
f:/test/b
f:/test/c
f:/test/a/a1
f:/test/a/a2
f:/test/a/a3
f:/test/b/b1
f:/test/b/b2
f:/test/b/b3
f:/test/c/c1
f:/test/c/c2
f:/test/c/c3