[python] os.walk() & os.path.walk()

os.walk(top) =>this method is acceptable with a valid path, and return a tuple,which consists of 3 elements being path string of path name,list of dictionary name, and list of file name everytime goint through with this pass down path. it would be empty if no path/pathname/filename is there 

1 import os
2 dir = r'C:\Intel'
3 for i in os.walk(dir):
4     print i

with output being:

('C:\\Intel', ['ExtremeGraphics', 'Logs'], [])

('C:\\Intel\\ExtremeGraphics', ['CUI'], [])
('C:\\Intel\\ExtremeGraphics\\CUI', ['Resource'], [])
('C:\\Intel\\ExtremeGraphics\\CUI\\Resource', [], [])
('C:\\Intel\\Logs', [], ['CPPC.log', 'DPTF.log', 'HIDEF.log', 'IntelAMT.log', 'IntelChipset.log', 'IntelCPHS.log', 'IntelGFX.log', 'IntelGFXCoin.log', 'IntelOCL.log'])

 

 

os.path.walk()

 

os.path.walk(top,func,arg)

top: one path that needs to iterate.

func: this is callback fun,which also has three arguments, defined format with func( arg,dirlist,filelist),arg passed from os.path.walk(top,func,arg)

arg:a tuple ,empty is acceptable.

 1 import os
 2 dirpath = r'c:\intel'
 3 def find_file(arg,dirname,files): 
 4     for file in files: 
 5         file_path=os.path.join(dirname,file)
 6         #print file_path
 7         if os.path.isfile(file_path): 
 8             print "find file:%s" %file_path
 9             #pass
10 
11 os.path.walk(dirpath,find_file,()) #empty tuple is passed down.

with output being:
c:\intel\ExtremeGraphics
c:\intel\Logs
c:\intel\ExtremeGraphics\CUI
c:\intel\ExtremeGraphics\CUI\Resource
c:\intel\Logs\CPPC.log
c:\intel\Logs\DPTF.log
c:\intel\Logs\HIDEF.log
c:\intel\Logs\IntelAMT.log
c:\intel\Logs\IntelChipset.log
c:\intel\Logs\IntelCPHS.log
c:\intel\Logs\IntelGFX.log
c:\intel\Logs\IntelGFXCoin.log
c:\intel\Logs\IntelOCL.log

Discrepency between os.walk() and os.path.walk() is dirname findings, the former only include dirname with files, and the latter is dirname with dirname and files mixed, if you want to find file path, you need to make a judge thru isfile() method in the process of os.path.walk()

前者只返回文件路径,后者返回文件路径和目录路径。

posted @ 2013-12-28 22:51  Yu Zi  阅读(1264)  评论(0编辑  收藏  举报