在水一万 发表于 2015-4-23 08:34:33

如何用Python实现目录遍历

  1. 基本实现
  # cat dirfile.py



import os
path='/tmp'
for dirpath,dirnames,filenames in os.walk(path):
for file in filenames:
fullpath=os.path.join(dirpath,file)
print fullpath
  执行结果如下:



# python dirfile.py
/tmp/yum.log
/tmp/pulse-3QSA3BbwpQ49/pid
/tmp/pulse-3QSA3BbwpQ49/native
/tmp/.esd-0/socket
  2. 在上例的基础上传递参数



import os,sys
path=sys.argv
for dirpath,dirnames,filenames in os.walk(path):
for file in filenames:
fullpath=os.path.join(dirpath,file)
print fullpath
  执行方式为:# python dirfile.py /tmp
  在这里,sys.argv是接受参数,也可以定义sys.argv接受第二个参数
  3. 如何用函数实现



import os,sys
path='/tmp'
def paths(path):
path_collection=[]
for dirpath,dirnames,filenames in os.walk(path):
for file in filenames:
fullpath=os.path.join(dirpath,file)
path_collection.append(fullpath)
return path_collection
for file in paths(path):
print file
  4. 如何封装成类



import os,sys
class diskwalk(object):
def __init__(self,path):
self.path = path
def paths(self):
path=self.path
path_collection=[]
for dirpath,dirnames,filenames in os.walk(path):
for file in filenames:
fullpath=os.path.join(dirpath,file)
path_collection.append(fullpath)
return path_collection
if __name__ == '__main__':
for file in diskwalk(sys.argv).paths():
print file
  PS:
  1> def __init__():函数,也叫初始化函数。
  self.path = path可以理解为初始化定义了1个变量。 在后面的def里面调用的时候必须要使用self.path而不能使用path
  2> __name__ == '__main__'
  模块是对象,并且所有的模块都有一个内置属性 __name__。一个模块的 __name__ 的值取决于您如何应用模块。如果 import 一个模块,那么模块__name__ 的值通常为模块文件名,不带路径或者文件扩展名。但是您也可以像一个标准的程序样直接运行模块,在这种情况下, __name__ 的值将是一个特别缺省"__main__"。上述类中加上__name__ == '__main__'的判断语句,可以直接在终端环境下执行python dirfile.py /tmp进行测试,不必非得在交互式环境下导入模块进行测试。
  具体可参考:http://www.iyunv.com/xuxm2007/archive/2010/08/04/1792463.html
  3> 关于参数self,可参考 http://blog.iyunv.com/taohuaxinmu123/article/details/38558377
  
页: [1]
查看完整版本: 如何用Python实现目录遍历