如何用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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM