zoukankan      html  css  js  c++  java
  • 如何用Python实现目录遍历

    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

  • 相关阅读:
    821. 字符的最短距离
    1122. 数组的相对排序
    258. 各位相加
    C++常见问题之二#define使用中的陷阱
    python进阶二_基本数据类型与操作
    DirectX10一变换(三)
    Android中编译工具链的改动----LLVM份量的增加
    DirectX10一矩阵代数(二)
    DirectX10一向量代数(一)
    基于asp.net + easyui框架,一步步学习easyui-datagrid——实现添加、编辑、删除(三)
  • 原文地址:https://www.cnblogs.com/ivictor/p/4362463.html
Copyright © 2011-2022 走看看