使用Python实现目录遍历

作者: secflag 分类: Python 发布时间: 2017-03-01 12:11

1. 基本实现

[root@localhost ~]# 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

执行结果如下:

[root@localhost ~]# 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[1]
for dirpath,dirnames,filenames in os.walk(path):
    for file in filenames:
            fullpath=os.path.join(dirpath,file)
            print fullpath

执行方式为:[root@localhost ~]# python dirfile.py /tmp

在这里,sys.argv[1]是接受参数,也可以定义sys.argv[2]接受第二个参数

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[1]).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.cnblogs.com/xuxm2007/archive/2010/08/04/1792463.html

3> 关于参数self,可参考 http://blog.csdn.net/taohuaxinmu123/article/details/38558377

文章转载自 http://www.cnblogs.com/ivictor/p/4362463.html