walk()递归遍历所有文件和目录

os.walk()方法:

返回一个3个元素的元组(dirpath, dirnames, filemnames)

  • dirpath: 列出指定目录下的路径
  • dirnames: 目录下的所有文件夹
  • filenames: 目录下的所有文件
 1 import os
 2 
 3 all_files = []
 4 path = os.getcwd()
 5 list_files = os.walk(path)
 6 
 7 for dirpath,dirnames,filenames in list_files:
 8     for dir in dirnames:
 9         all_files.append(os.path.join(dirpath,dir))
10     for file in filenames:
11         all_files.append((os.path.join(dirpath,file)))
12 
13 
14 for file in all_files:
15     print(file)