1 使用栈遍历目录
import os
path = r"E:\python1901\chengxu"
def stackgetdir(path):
stack = []
stack.append(path)
while len(stack) > 0:
path = stack.pop()
fileList = os.listdir(path)
for filename in fileList:
abspath = os.path.join(path,filename)
if os.path.isdir(abspath):
print("目录",filename)
stack.append(abspath)
else:
print("文件",filename)
stackgetdir(path)
2递归遍历目录
'''
递归遍历目录
'''
import os
path = r"E:\python1901\chengxu"
def getallfile(path):
fileList = os.listdir(path)
for filename in fileList:
abspath = os.path.join(path,filename)
if os.path.isdir(abspath):
print("目录",filename)
getallfile(abspath)
else:
print("文件",filename)
print(getallfile(path))
3 队列方法
import os
import collections
path= r"E:\python1901\chengxu"
def getAllDirQU(path):
queue = collections.deque()
queue.append(path)
while len(queue) != 0:
dirPath = queue.popleft()
fileList = os.listdir(dirPath)
for fileName in fileList:
fileAbsPath = os.path.join(dirPath, fileName)
if os.path.isdir(fileAbsPath):
print("目录:", fileName)
queue.append(fileAbsPath)
else:
print("普通文件:", fileName)
print(getAllDirQU(path))