標籤:python 遍曆
1.os.popen運行shell列表命令
def traverseDirByShell(path): for f in os.popen(‘ls ‘ + path): print f.strip()
2.利用glob模組
glob.glob(path)返回帶目錄的檔案名稱.萬用字元和shell相似.path不能包含shell變數.
def traverseDirByGlob(path): path = os.path.expanduser(path) for f in glob(path + ‘/*‘): print f.strip()
3.利用os.listdir(推薦)
該方法返回不帶根目錄的檔案名稱或子目錄名
def traverseDirByListdir(path): path = os.path.expanduser(path) for f in os.listdir(path): print f.strip()
4.利用os.walk(推薦)
返回一個包含3個項目的元組:目前的目錄名稱,子目錄名稱,子檔案名稱
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))
整合代碼:
#!/usr/bin/pythonimport osfrom glob import globdef printSeparator(func): def deco(path): print("call method %s, result is:" % func.__name__) print("-" * 40) func(path) print("=" * 40) return deco@printSeparatordef traverseDirByShell(path): for f in os.popen(‘ls ‘ + path): print f.strip()@printSeparatordef traverseDirByGlob(path): path = os.path.expanduser(path) for f in glob(path + ‘/*‘): print f.strip()@printSeparatordef traverseDirByListdir(path): path = os.path.expanduser(path) for f in os.listdir(path): print f.strip()@printSeparatordef 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)
Python遍曆目錄的多種方式