os.walk()
def walk(top, topdown=True, οnerrοr=None, followlinks=False):
"""Directory tree generator.
For each directory in the directory tree rooted at top (including topitself, but excluding '.' and '..'), yields a 3-tuple
dirpath, dirnames, filenames
对于top文件夹中的所有层级的文件夹(包含top文件夹本身以及它里面所有的子文件夹),都会返回一个三元组
dirpath, dirnames, filenames
dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories(all level subdirectories) in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists are just names, with no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).
dirpath是一个string,它的值是当前正在访问的目录(目录也就是文件夹)的路径。dirnames是当前访问的目录(即dirpath)下面的所有目录名字的列表,但是这个列表不包含dirpath目录下再下一级的目录。filenames是一个列表,它包含了当前访问的目录(即dirpath)下面所有非目录的文件的名字,它只包含名字而已。如果要得到dirpath下面一个文件的完整路径,应该使用os.path.join(dirpath, name)。
举例:E:\CV\data\cifar-100-png\train路径中有20个目录,如图1所示。而每个目录下面又有5个目录,如图2所示。在这5个目录中,每个目录又含有500张图片,如图3所示。
图1
图2
图3
代码如下
import os
import shutil
def move_dirs_to_one_dir(dir_path_top):
"""
测试os.walk()函数功能
"""
test_result = []
for path, dirs, files in os.walk(dir_path_top, topdown=True): # topdown=True
test_result.append((path, dirs, files))
a = 0 # 用于debug
if __name__ == '__main__':
dir_path_top = r'E:\CV\data\cifar-100-png\train'
move_dirs_to_one_dir(dir_path_top)
test_result的结果如下:
图4
图5
因为设置topdown=True,所以是从顶层目录开始往最底层目录访问,test_result中第一个元素对应的dirpath就是顶层目录E:\CV\data\cifar-100-png\train。它里面有20个目录,所以test_result中第一个元素对应的dirnames包含了这20个目录的名字。而当前访问的目录train中没有图片或者其它的非目录文件,所以它对应的files为空。
而第20个元素,它已经在访问20个目录中的下一级目录了,此时访问的是E:\CV\data\cifar-100-png\train\food_containers\bottle这个目录,所以此时的dirpath就是E:\CV\data\cifar-100-png\train\food_containers\bottle。bottle这个目录中没有子目录,所以它对应的dirnames为空。bottle目录中有500张图片,所以对应的files列表中包含了这500张图片的名字。