1、熟悉os.stat和stat模塊中的方S_ISDIR、S_ISREG
2、遞歸調用
import os, sys
from stat import *
def walktree(top, callback):
'''recursively descend the directory tree rooted at top,
calling the callback function for each regular file'''
for f in os.listdir(top):
pathname = os.path.join(top, f)
mode = os.stat(pathname).st_mode
if S_ISDIR(mode):
# It's a directory, recurse into it
print()
print(pathname)
walktree(pathname, callback)
elif S_ISREG(mode):
# It's a file, call the callback function
callback(f)#此行的callback 相當於 visitfile函數的名字
else:
# Unknown file type, print a message
print('Skipping %s' % pathname)
def visitfile(file):
print('文件名', file)
if __name__ == '__main__':
print(sys.argv[1])
walktree(sys.argv[1], visitfile)
#命令行中輸入 python listFile.py \\192.168.0.188\h\成品目錄
截取部分運行結果如下圖: