import os
import os.path
# this folder is custom
rootdir="D:/360Downloads/testFile1"
for parent,dirnames,filenames in os.walk(rootdir):
#case 1:
for dirname in dirnames:
print("parent folder is:" + parent)
print("dirname is:" + dirname)
#case 2
for filename in filenames:
print("parent folder is:" + parent)
print("filename with full path:"+ os.path.join(parent,filename))
* os.walk返回一个三元组.其中dirnames是所有文件夹名字(不包含路径),filenames是所有文件的名字(不包含路径).parent表示父目录.
* case1 演示了如何遍历所有目录.
* case2 演示了如何遍历所有文件.
* os.path.join(dirname,filename) : 将形如"/a/b/c"和"d.java"变成/a/b/c/d.java". '''
效果图: