[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()

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

转载于:https://www.cnblogs.com/yuzi/p/3495898.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值