假如有下述文件组织结构
储备知识:
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
print(list(zip(a,b,c)))
结果:
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
for h, i, j in zip(a, b, c):
print("h=", h, "i=", i, "j=", j)
结果:
h= 1 i= 4 j= 7
h= 2 i= 5 j= 8
h= 3 i= 6 j= 9
示例代码1:
import os
path = r"F:\Test"
for root, dirs, files in os.walk(path):
print("Root=", root, '\t', "dirs=", dirs, '\t',"files=", files)
结果:
Root= F:\Test dirs= ['SubTest1', 'SubTest2'] files= ['Test.docx', 'Test.txt']
Root= F:\Test\SubTest1 dirs= ['ThirdLayer'] files= ['Test1.docx', 'Test1.txt']
Root= F:\Test\SubTest1\ThirdLayer dirs= [] files= ['Test3.docx', 'Test3.txt']
Root= F:\Test\SubTest2 dirs= [] files= ['Test2.docx', 'Test2.txt']
结果分析:
-
先从根目录进行遍历,读取跟目录的文件夹和文件。
-
以根目录第一个子目录为新的根目录,读取其文件夹和文件。
-
再以2中的第一个子文件夹为根目录,读取文件夹和文件。(这个应该是属于树结构里面的自上而下深度遍历算法)
-
读取1步骤里面其他子目录的文件夹和文件。
示例代码2:(修改topdown 为False)
import os
path = r"F:\Test"
for root, dirs, files in os.walk(path,topdown=False):
print("Root=", root, '\t', "dirs=", dirs, '\t',"files=", files)
结果:
Root= F:\Test\SubTest1\ThirdLayer dirs= [] files= ['Test3.docx', 'Test3.txt']
Root= F:\Test\SubTest1 dirs= ['ThirdLayer'] files= ['Test1.docx', 'Test1.txt']
Root= F:\Test\SubTest2 dirs= [] files= ['Test2.docx', 'Test2.txt']
Root= F:\Test dirs= ['SubTest1', 'SubTest2'] files= ['Test.docx', 'Test.txt']
分析:实质一样,不过用的是自下而上的深度遍历算法。
总结:
- 文件的全路径: 从上面的结果可以看出,文件的全路径,应该是os.path.join(root, files)
for root, dirs, files in os.walk(path,topdown=False):
for f in files:
print(os.path.join(root,f))
结果为:
F:\Test\SubTest1\ThirdLayer\Test3.docx
F:\Test\SubTest1\ThirdLayer\Test3.txt
F:\Test\SubTest1\Test1.docx
F:\Test\SubTest1\Test1.txt
F:\Test\SubTest2\Test2.docx
F:\Test\SubTest2\Test2.txt
F:\Test\Test.docx
F:\Test\Test.txt
2.统计有多少文件
import os
path = r"F:\Test"
total = 0
for root, dirs, files in os.walk(path, topdown=False):
# print("Root=", root, '\t', "dirs=", dirs, '\t',"files=", files)
for f in files:
total += 1
print(total)
- 如果你要数路径下有多少个文件夹,其实很简单就是所有的root数目-1,因为root数目包含path文件夹。
- 如果以文件作为path路径会怎样? 返回空。
import os
path = r"F:\Test"
for root, dirs, files in os.walk(path,topdown=False):
print("Root=", root, '\t', "dirs=", dirs, '\t',"files=", files)
结果:
- 如果以一个不存在的文件夹为路径作为path会怎样?这里假定如果onerror = None,返回为空。
import os
path = r"F:\Test1"
for root, dirs, files in os.walk(path,topdown=False):
print("Root=", root, '\t', "dirs=", dirs, '\t',"files=", files)
结果: