分别用两种方法实现:
第一种:使用os.walk:
-
# -*- coding: utf-8 -*-
-
import os
-
def Test1(rootDir):
-
list_dirs = os.walk(rootDir)
-
for root, dirs, files in list_dirs:
-
for d in dirs:
-
print os.path.join(root, d)
-
for f in files:
-
print os.path.join(root, f)
第二种:使用os.listdir:
-
# -*- coding: utf-8 -*-
-
import os
-
def Test2(rootDir):
-
for lists in os.listdir(rootDir):
-
path = os.path.join(rootDir, lists)
-
print path
-
if os.path.isdir(path):
-
Test2(path)
这两种到底有什么区别呢?
这里先建立一个测试目录E:\test,目录结构如下:
-
E:\TEST
-
│--A
-
│ │--A-A
-
│ │ │--A-A-A.txt
-
│ │--A-B.txt
-
│ │--A-C
-
│ │ │--A-B-A.txt
-
│ │--A-D.txt
-
│--B.txt
-
│--C
-
│ │--C-A.txt
-
│ │--C-B.txt
-
│--D.txt
-
│--E
下面通过运行如下代码:
-
Test1('E:\TEST')
-
print '======================================='
-
Test2('E:\TEST')
输出结果为:
-
>>>
-
E:\TEST\A
-
E:\TEST\C
-
E:\TEST\E
-
E:\TEST\B.txt
-
E:\TEST\D.txt
-
E:\TEST\A\A-A
-
E:\TEST\A\A-C
-
E:\TEST\A\A-B.txt
-
E:\TEST\A\A-D.txt
-
E:\TEST\A\A-A\A-A-A.txt
-
E:\TEST\A\A-C\A-B-A.txt
-
E:\TEST\C\C-A.txt
-
E:\TEST\C\C-B.txt
-
=======================================
-
E:\TEST\A
-
E:\TEST\A\A-A
-
E:\TEST\A\A-A\A-A-A.txt
-
E:\TEST\A\A-B.txt
-
E:\TEST\A\A-C
-
E:\TEST\A\A-C\A-B-A.txt
-
E:\TEST\A\A-D.txt
-
E:\TEST\B.txt
-
E:\TEST\C
-
E:\TEST\C\C-A.txt
-
E:\TEST\C\C-B.txt
-
E:\TEST\D.txt
-
E:\TEST\E
-
>>>
可以看出,对于第一种方法,输出总是先文件夹后文件名的,对于第二种,则是按照目录树结构以及按照首字母排序进行输出的。
补充加入:对某目录下(包括子目录)的所有.ppm文件改为.jpg文件。
-
from PIL import Image
-
import os
-
import os.path
-
def change_format(rootDir):
-
for root, dirs, files in os.walk(rootDir):
-
for file in files:
-
if os.path.splitext(file)[1] == '.ppm':
-
im = Image.open(os.path.join(root, file))
-
filename = os.path.join(root, file)
-
im.save(os.path.splitext(filename)[0] + '.jpg', 'JPEG')
-
if __name__ == '__main__':
-
_dir = "your directory"
-
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]为文件名