1.os.popen running the Shell List command
def traverseDirByShell(path): forin os.popen(‘ls ‘ + path): print f.strip()
2. Using the Glob module
Glob.glob (path) returns the file name with the directory. Wildcard characters are similar to shells. Path cannot contain shell variables.
def traverseDirByGlob(path): path = os.path.expanduser(path) forin‘/*‘): print f.strip()
3. Using Os.listdir (recommended)
The method returns the name of the file or subdirectory without the root directory
def traverseDirByListdir(path): path = os.path.expanduser(path) forin os.listdir(path): print f.strip()
4. Using Os.walk (recommended)
Returns a tuple containing 3 items: current directory name, subdirectory name, sub-file name
def traverseDirByOSWalk(path): path = os.path.expanduser(path) forin os.walk(path): #print(‘dirname is %s, subdir is %s, subfile is %s‘ % (dirname, subdir, subfile)) print(‘[‘‘]‘) forin subfile: print(os.path.join(dirname, f))
Integration code:
#!/usr/bin/pythonImportOs fromGlobImportGlob def printseparator(func): def deco(path):Print"Call method%s, result is:"% func.__name__) Print ("-"* +) func (path) print ("="* +)returnDeco@printSeparator def Traversedirbyshell(path): forFinchOs.popen (' ls '+ path):PrintF.strip ()@printSeparator def traversedirbyglob(path):Path = Os.path.expanduser (path) forFinchGlob (path +'/* '):PrintF.strip ()@printSeparator def traversedirbylistdir(path):Path = Os.path.expanduser (path) forFinchOs.listdir (PATH):PrintF.strip ()@printSeparator def traversedirbyoswalk(path):Path = Os.path.expanduser (path) for(DirName, SubDir, Subfile)inchOs.walk (PATH):#print (' dirname is%s, SubDir was%s, Subfile is%s '% (dirname, subdir, subfile))Print' ['+ DirName +'] ') forFinchSubfile:print (Os.path.join (dirname, F))if__name__ = =' __main__ ': Path =R ' ~/src/py 'Traversedirbyglob (path) traversedirbyglob (path) traversedirbylistdir (path) traversedirbyoswalk (path)
Many ways Python traverses a directory