#方法1 递归 import os def getAllDirAndFile(sourcePath): if not os.path.exists(sourcePath): return pathList=os.listdir(sourcePath) # print(pathList) for pathName in pathList: absPath=os.path.join(sourcePath,pathName) if os.path.isdir(absPath): getAllDirAndFile(absPath) if os.path.isfile(absPath): print(absPath) if __name__ == '__main__': sourcePath = r"F:\python\lianxi" getAllDirAndFile(sourcePath)
#方法2 广度遍历(队列) import os import collections def getAllDirAndFile(sourcePath): if not os.path.exists(sourcePath): return queue=collections.deque() queue.append(sourcePath) while True: if len(queue)==0: break path=queue.popleft() for pathName in os.listdir(path): absPath=os.path.join(path,pathName) if os.path.isdir(absPath): queue.append(absPath) if os.path.isfile(absPath): print(absPath) if __name__ == '__main__': sourcePath=r"F:\python\resource\day11" getAllDirAndFile(sourcePath)