Python遍历目录的4种方法实例介绍
1.os.popen运行shell列表命令
deftraverseDirByShell(path): forfinos.popen('ls'+path): printf.strip()
2.利用glob模块
glob.glob(path)返回带目录的文件名.通配符和shell相似.path不能包含shell变量.
deftraverseDirByGlob(path): path=os.path.expanduser(path) forfinglob(path+'/*'): printf.strip()
3.利用os.listdir(推荐)
该方法返回不带根目录的文件名或子目录名
deftraverseDirByListdir(path): path=os.path.expanduser(path) forfinos.listdir(path): printf.strip()
4.利用os.walk(推荐)
返回一个包含3个项目的元组:当前目录名称,子目录名称,子文件名称
deftraverseDirByOSWalk(path): path=os.path.expanduser(path) for(dirname,subdir,subfile)inos.walk(path): #print('dirnameis%s,subdiris%s,subfileis%s'%(dirname,subdir,subfile)) print('['+dirname+']') forfinsubfile: print(os.path.join(dirname,f))
整合代码:
#!/usr/bin/python importos fromglobimportglob
defprintSeparator(func): defdeco(path): print("callmethod%s,resultis:"%func.__name__) print("-"*40) func(path) print("="*40) returndeco
@printSeparator deftraverseDirByShell(path): forfinos.popen('ls'+path): printf.strip()
@printSeparator deftraverseDirByGlob(path): path=os.path.expanduser(path) forfinglob(path+'/*'): printf.strip()
@printSeparator deftraverseDirByListdir(path): path=os.path.expanduser(path) forfinos.listdir(path): printf.strip()
@printSeparator deftraverseDirByOSWalk(path): path=os.path.expanduser(path) for(dirname,subdir,subfile)inos.walk(path): #print('dirnameis%s,subdiris%s,subfileis%s'%(dirname,subdir,subfile)) print('['+dirname+']') forfinsubfile: print(os.path.join(dirname,f))
if__name__=='__main__': path=r'~/src/py' traverseDirByGlob(path)
traverseDirByGlob(path)
traverseDirByListdir(path)
traverseDirByOSWalk(path)