我们使用os.walk(rootpath)遍历rootpath路径下所有的文件和目录。
需要注意的一点是:
对于rootpath下的每一个子目录(包括递归的子目录和根目录本身’.’),都会返回一个3-tuple (dirpath, dirnames, filenames).
dirpath是递归子目录的路径,dirnames是递归子目录dirpath下所有子目录(不包括递归的子目录和根目录本身’.’)的列表,filenames是dirpath下所有的文件(不包含递归文件)。
# walkpath.py
import os
for dirpath, dirs, files in os.walk('.') :
print('dirpath is ' + str(dirpath))
print('subdirlist is ' + str(dirs))
print('subfilelist is ' + str(files))
print('')
举例:
windows下使用以下命令查看文件树:
F:\Python code>tree /f # /f 表示显示文件名
卷 HHD 的文件夹 PATH 列表
卷序列号为 92AA-58EA
F:.
│ new.txt
│ walkpath.py
│
├─data structure
│ └─ex0
│ 1.py
│ 2.py
│ 3.py
│ 4.py
│ 5.py
│
├─summer exercise
│ ex1_1.py
│ ex1_2.py
│ ex1_3.py
│ ex2_1.py
│ ex2_2.py
│ ex2_3.py
│ ex_G.py
│ ex_H.py
│ ex_Ipy.py
│ ex_J.py
│ ex_K.py
│ ex_Lpy.py
│ ex_M.py
│ ex_N.py
│ ex_O.py
│ ex_P.py
│ ex_Q.py
│ ex_R.py
│ ex_S.py
│ ex_T.py
│ ex_U.py
│ ex_V.py
│ ex_W.py
│ ex_X.py
│
└─test code
hello.py
hello_world.py
运行walkpath.py所得结果如下:
1.观察到dirpath包含’.’
2.递归显示了子子目录./data structure/ex0
F:\Python code>python walkpath.py
dirpath is .
subdirlist is ['data structure', 'summer exercise', 'test code']
subfilelist is ['new.txt', 'walkpath.py']
dirpath is .\data structure
subdirlist is ['ex0']
subfilelist is []
dirpath is .\data structure\ex0
subdirlist is []
subfilelist is ['1.py', '2.py', '3.py', '4.py', '5.py']
dirpath is .\summer exercise
subdirlist is []
subfilelist is ['ex1_1.py', 'ex1_2.py', 'ex1_3.py', 'ex2_1.py', 'ex2_2.py', 'ex2_3.py', 'ex_G.py', 'ex_H.py', 'ex_Ipy.py', 'ex_J.py', 'ex_K.py', 'ex_Lpy.py', 'ex_M.py', 'ex_N.py', 'ex_O.py', 'ex_P.py', 'ex_Q.py', 'ex_R.py', 'ex_S.py', 'ex_T.py', 'ex_U.py', 'ex_V.py', 'ex_W.py', 'ex_X.py']
dirpath is .\test code
subdirlist is []
subfilelist is ['hello.py', 'hello_world.py']
'''