os.walk文件遍历

 for root , dirs, files in os.walk(path):

知识点:

代码中的root为str类型,dirs为list类型,files为list类型

当root为/test时,dirs列表中是/test下的目录,files列表是/test下的文件

当root为/test/aa时,dirs列表则为/test/aa下的目录,fiels列表是/test/aa下的文件

这些名字不包含路径信息,如果需要得到全路径,需要使用os.path.join(dirpath, name).

[python] view plain copy 
1.#!/usr/bin/python  
2.#coding=utf-8  
3.import os  
4.def dirlist(path):  
5.    for root,dirs,files in os.walk(path):  #将os.walk在元素中提取的值,分别放到root(根目录),dirs(目录名),files(文件名)中。  
6.        for file in files:  
7.            print os.path.join(root,file)  #根目录与文件名组合,形成绝对路径。  
8.if __name__=='__main__':  
9.    path = '/test'  
10.    dirlist(path)  

遍历文件夹并删除特定格式文件的示例

 

 1 #!/usr/bin/python
 2 # -*- coding: utf-8 -*-
 3 import os
 4 def del_files(path):
 5     for root , dirs, files in os.walk(path):
 6         for name in files:
 7             if name.endswith(".tmp"):
 8                 os.remove(os.path.join(root, name))
 9   print ("Delete File: " + os.path.join(root, name))
10 # test
11 if __name__ == "__main__":
12     path = '/tmp'
13     del_files(path)

 

通过for循环即可完成目录的递归

 1 #!/usr/bin/python
 2 # -*- coding: gbk -*-
 3   
 4 # os.walk()的使用  
 5 import os  
 6   
 7 # 枚举dirPath目录下的所有文件  
 8   
 9 def main():  
10 #begin  
11     fileDir = "F:" + os.sep + "aaa"     # 查找F:\aaa 目录下    
12     for root, dirs, files in os.walk(fileDir):  
13     #begin  
14         for dir in dirs:  
15         #begin  
16             print(os.path.join(root, dir))  
17         #end  
18         for file in files:  
19         #begin  
20             print(os.path.join(root, file))  
21         #end  
22     #end  
23     os.system("pause")  
24 #end  
25   
26 if __name__ == '__main__':  
27 #begin  
28     main()  
29 #end

 

posted on 2017-11-30 12:59  gis木棉鱼  阅读(717)  评论(1编辑  收藏  举报