您的位置:首页 > 编程语言 > Python开发

用多种方式独立完成目录的遍历,目录的复制

2018-01-12 17:45 399 查看
#方法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)
whi
4000
le 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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息