如何優雅的使用 Python 實現檔案遞迴遍曆

來源:互聯網
上載者:User

標籤:cas   ssi   The   int   not   沒有   就會   功能實現   函數   

今天有個指令碼需要遍曆擷取某指定檔案夾下面的所有檔案,我記得很早前也實現過檔案遍曆和目錄遍曆的功能,於是找來看一看,嘿,不看不知道,看了嚇一跳,原來之前我竟然用了這麼搓的實現。

先發出來看看:

def getallfiles(dir):"""遍曆擷取指定檔案夾下面所有檔案"""    if os.path.isdir(dir):        filelist = os.listdir(dir)        for ret in filelist:            filename = dir + "\\" + ret            if os.path.isfile(filename):                print filenamedef getalldirfiles(dir, basedir):"""遍曆擷取所有子檔案夾下面所有檔案"""    if os.path.isdir(dir):        getallfiles(dir)        dirlist = os.listdir(dir)        for dirret in dirlist:            fullname = dir + "\\" + dirret            if os.path.isdir(fullname):                getalldirfiles(fullname, basedir)

我是用了 2 個函數,並且每個函數都用了一次 listdir,只是一次用來過濾檔案,一次用來過濾檔案夾,如果只是從功能實現上看,一點問題沒有,但是這…太不優雅了吧。

開始著手最佳化,方案一:

def getallfiles(dir):"""使用listdir迴圈遍曆"""    if not os.path.isdir(dir):        print dir        return    dirlist = os.listdir(dir)    for dirret in dirlist:        fullname = dir + "\\" + dirret        if os.path.isdir(fullname):            getallfiles(fullname)        else:            print fullname

從可以看到,我把兩個函數合并成了一個,只調用了一次 listdir,把檔案和檔案夾用 if~else~ 進行了分支處理,當然,自我調用的迴圈還是存在。

有木有更好的方式呢?網上一搜一大把,原來有一個現成的 os.walk() 函數可以用來處理檔案(夾)的遍曆,這樣最佳化下就更簡單了。

方案二:

def getallfilesofwalk(dir):"""使用listdir迴圈遍曆"""    if not os.path.isdir(dir):        print dir        return    dirlist = os.walk(dir)    for root, dirs, files in dirlist:        for file in files:            print os.path.join(root, file)

只是從代碼實現上看,方案二是最優雅簡潔的了,但是再翻看 os.walk() 實現的源碼就會發現,其實它內部還是調用的 listdir 完成具體的功能實現,只是它對輸出結果做了下額外的處理而已。

附上os.walk()的源碼:

from os.path import join, isdir, islink# We may not have read permission for top, in which case we can‘t# get a list of the files the directory contains.  os.path.walk# always suppressed the exception then, rather than blow up for a# minor reason when (say) a thousand readable directories are still# left to visit.  That logic is copied here.try:    # Note that listdir and error are globals in this module due    # to earlier import-*.    names = listdir(top)except error, err:    if onerror is not None:        onerror(err)    returndirs, nondirs = [], []for name in names:    if isdir(join(top, name)):        dirs.append(name)    else:        nondirs.append(name)if topdown:    yield top, dirs, nondirsfor name in dirs:    path = join(top, name)    if followlinks or not islink(path):        for x in walk(path, topdown, onerror, followlinks):            yield xif not topdown:    yield top, dirs, nondirs

至於 listdir 和 walk 在輸出時的不同點,主要就是 listdir 預設是按照檔案和檔案夾存放的字母順序進行輸出,而 walk 則是先輸出頂級檔案夾,然後是頂級檔案,再輸出第二級檔案夾,以及第二級檔案,以此類推,具體大家可以把上面指令碼拷貝後自行驗證。

以上,如果覺得有用,請幫忙轉寄分享,不甚感激。

如何優雅的使用 Python 實現檔案遞迴遍曆

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.