一. 用递归遍历目录
import os
def getAllDirAndFile ( pathDir) :
if not os. path. isdir( pathDir) :
return
listNames = os. listdir( pathDir)
for name in listNames:
absPath = os. path. join( pathDir, name)
if os. path. isdir( absPath) :
print ( "目录:%s" % ( absPath) )
getAllDirAndFile( absPath)
if os. path. isfile( absPath) :
print ( "文件:%s" % ( absPath) )
getAllDirAndFile( path)
二. 栈实现深度遍历
import os
import collections
def getAllDirAndFile ( pathDir) :
if not os. path. isdir( pathDir) :
return
strack = collections. deque( )
strack. append( pathDir)
while True :
if len ( strack) == 0 :
break
path = strack. pop( )
listNames = os. listdir( path)
for name in listNames:
absPath = os. path. join( path, name)
if os. path. isfile( absPath) :
print ( "文件:%s" % ( absPath) )
if os. path. isdir( absPath) :
print ( "目录:%s" % ( absPath) )
strack. append( absPath)
path = r"C:\Users\Administrator\Desktop"
getAllDirAndFile( path)
3. 队列实现广度遍历
import os
import collections
def getAllDirAndFile ( pathDir) :
if not os. path. isdir( pathDir) :
return
queue = collections. deque( )
queue. append( pathDir)
while True :
if len ( queue) == 0 :
break
path = queue. popleft( )
listNames = os. listdir( path)
for name in listNames:
absPath = os. path. join( path, name)
if os. path. isfile( absPath) :
print ( "文件:%s" % ( absPath) )
if os. path. isdir( absPath) :
print ( "目录:%s" % ( absPath) )
queue. append( absPath)
getAllDirAndFile( r"F:\Program Files" )