Python遍历文件夹的两种方法比较

分别用两种方法实现: 

第一种:使用os.walk:

 
  1. # -*- coding: utf-8 -*-

  2. import os

  3. def Test1(rootDir):

  4. list_dirs = os.walk(rootDir)

  5. for root, dirs, files in list_dirs:

  6. for d in dirs:

  7. print os.path.join(root, d)

  8. for f in files:

  9. print os.path.join(root, f)

第二种:使用os.listdir:

 

 
  1. # -*- coding: utf-8 -*-

  2. import os

  3. def Test2(rootDir):

  4. for lists in os.listdir(rootDir):

  5. path = os.path.join(rootDir, lists)

  6. print path

  7. if os.path.isdir(path):

  8. Test2(path)

这两种到底有什么区别呢?

这里先建立一个测试目录E:\test,目录结构如下:

 
  1. E:\TEST

  2. │--A

  3. │ │--A-A

  4. │ │ │--A-A-A.txt

  5. │ │--A-B.txt

  6. │ │--A-C

  7. │ │ │--A-B-A.txt

  8. │ │--A-D.txt

  9. │--B.txt

  10. │--C

  11. │ │--C-A.txt

  12. │ │--C-B.txt

  13. │--D.txt

  14. │--E


下面通过运行如下代码:

 

 
  1. Test1('E:\TEST')

  2. print '======================================='

  3. Test2('E:\TEST')


输出结果为:

 
  1. >>>

  2. E:\TEST\A

  3. E:\TEST\C

  4. E:\TEST\E

  5. E:\TEST\B.txt

  6. E:\TEST\D.txt

  7. E:\TEST\A\A-A

  8. E:\TEST\A\A-C

  9. E:\TEST\A\A-B.txt

  10. E:\TEST\A\A-D.txt

  11. E:\TEST\A\A-A\A-A-A.txt

  12. E:\TEST\A\A-C\A-B-A.txt

  13. E:\TEST\C\C-A.txt

  14. E:\TEST\C\C-B.txt

  15. =======================================

  16. E:\TEST\A

  17. E:\TEST\A\A-A

  18. E:\TEST\A\A-A\A-A-A.txt

  19. E:\TEST\A\A-B.txt

  20. E:\TEST\A\A-C

  21. E:\TEST\A\A-C\A-B-A.txt

  22. E:\TEST\A\A-D.txt

  23. E:\TEST\B.txt

  24. E:\TEST\C

  25. E:\TEST\C\C-A.txt

  26. E:\TEST\C\C-B.txt

  27. E:\TEST\D.txt

  28. E:\TEST\E

  29. >>>

可以看出,对于第一种方法,输出总是先文件夹后文件名的,对于第二种,则是按照目录树结构以及按照首字母排序进行输出的。

 

补充加入:对某目录下(包括子目录)的所有.ppm文件改为.jpg文件。

 

 
  1. from PIL import Image

  2. import os

  3. import os.path

  4.  
  5. def change_format(rootDir):

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

  7. for file in files:

  8. if os.path.splitext(file)[1] == '.ppm':

  9. im = Image.open(os.path.join(root, file))

  10. filename = os.path.join(root, file)

  11. im.save(os.path.splitext(filename)[0] + '.jpg', 'JPEG')

  12.  
  13. if __name__ == '__main__':

  14. _dir = "your directory"

  15. change_format(_dir)


root 为 path(一直到file名字(除去文件名字)),file只是文件名字加上扩展名
此处os.path.join(root,file)为absolute path,os.path.splitext(file)[1]为扩展名(os.path.splitext(file)[1][1:]为ppm不带.),os.path.splitext(file)[0]为文件名

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值