Examples of four ways Python can traverse a directory
- 2020-05-09 18:44:48
- OfStack
1.os.popen run the shell list command
def traverseDirByShell(path):
for f in os.popen('ls ' + path):
print f.strip()
2. Use the glob module
glob.glob (path) returns the file name with the directory. The wildcard is similar to shell.path cannot contain the shell variable.
def traverseDirByGlob(path):
path = os.path.expanduser(path)
for f in glob(path + '/*'):
print f.strip()
3. Use os.listdir(recommended)
This method returns the file name or subdirectory name without the root directory
def traverseDirByListdir(path):
path = os.path.expanduser(path)
for f in os.listdir(path):
print f.strip()
4. Use os.walk(recommended)
Returns a tuple containing three items: the current directory name, the subdirectory name, and the subfile name
def traverseDirByOSWalk(path):
path = os.path.expanduser(path)
for (dirname, subdir, subfile) in os.walk(path):
#print('dirname is %s, subdir is %s, subfile is %s' % (dirname, subdir, subfile))
print('[' + dirname + ']')
for f in subfile:
print(os.path.join(dirname, f))
Integrated code:
#!/usr/bin/python
import os
from glob import glob
def printSeparator(func):
def deco(path):
print("call method %s, result is:" % func.__name__)
print("-" * 40)
func(path)
print("=" * 40)
return deco
@printSeparator
def traverseDirByShell(path):
for f in os.popen('ls ' + path):
print f.strip()
@printSeparator
def traverseDirByGlob(path):
path = os.path.expanduser(path)
for f in glob(path + '/*'):
print f.strip()
@printSeparator
def traverseDirByListdir(path):
path = os.path.expanduser(path)
for f in os.listdir(path):
print f.strip()
@printSeparator
def traverseDirByOSWalk(path):
path = os.path.expanduser(path)
for (dirname, subdir, subfile) in os.walk(path):
#print('dirname is %s, subdir is %s, subfile is %s' % (dirname, subdir, subfile))
print('[' + dirname + ']')
for f in subfile:
print(os.path.join(dirname, f))
if __name__ == '__main__':
path = r'~/src/py'
traverseDirByGlob(path)
traverseDirByGlob(path)
traverseDirByListdir(path)
traverseDirByOSWalk(path)