【面试】用os的walk遍历文件夹及子文件下下的所有文件

代码:

# coding:utf-8
import os


def getallfiles(path):
    allfile = []
    for dirpath, dirnames, filenames in os.walk(path):
        for dir in dirnames:
            allfile.append(os.path.join(dirpath, dir))
        for name in filenames:
            allfile.append(os.path.join(dirpath, name))
    return allfile


if __name__ == '__main__':
    path = r"D:\testdir"
    allfile = getallfiles(path)
    for file in allfile:
        print(file)

 

你可能感兴趣的:(面试)