Python遍曆檔案夾,

來源:互聯網
上載者:User

Python遍曆檔案夾,

許多次需要用python來遍曆目錄下檔案, 這一次就整理了記錄在這裡。

隨實際工作,不定期更新。

 1 import os 2  3 class FileTraversal: 4  5     def __init__(self, rootpath): 6  7         self.rootpath = rootpath 8  9         #從頂至底的遍曆(在剪短的代碼裡,我比較喜歡這清晰的變數名)10         self.tracersal_from_top_to_down = True11 12         #遍曆發生錯誤的時候的回呼函數13         #函數參數為一個OSError型別參數14         #檔案名稱會作為錯誤參數的一個屬性 , 如 error.filename15         self.on_error_func = None16 17         #是否變數連結檔案(如:軟連結、永久連結、windows上的捷徑)18         self.follow_links = False19     20     '''21         設定遍曆順序22     '''23     def setTopToDown(self, from_top_to_dowm=True):24         self.tracersal_from_top_to_down = from_top_to_dowm25         return self26     '''27         設定錯誤回呼函數28     '''29     def setErrorFunc(self, err_func=None):30         self.on_error_func = err_func31         return self32     '''33         設定是否遍曆串連檔案34     '''35     def setFollowLinks(self, follow_links = False):36         self.follow_links = follow_links37         return self38 39     '''40         擷取迭代器41     '''42     def getGenerator(self):43         return os.walk(self.rootpath, self.tracersal_from_top_to_down, self.on_error_func, self.follow_links)44 45     '''46         擷取所有檔案47         @param absolute_path: 是否返回絕對路徑,或者僅僅檔案名稱48     '''49     def getFiles(self,absolute_path=True):50         files = []51         for parent,dirnames,filenames in self.getGenerator():    #三個參數:分別返回1.父目錄 2.所有檔案夾名字(不含路徑) 3.所有檔案名稱字52             for file in filenames:53                 filepath = os.path.join(parent,file)54                 files.append( filepath if absolute_path else file)55         return files56 57     '''58         擷取目前的目錄下所有的檔案(不遞迴遍曆)59         @60     '''61     def getThisLevelFiles(self,absolute_path=True):62         files = []63         all_in_dir = os.listdir(self.rootpath)64         for file in all_in_dir:65             filepath = os.path.join(self.rootpath, file)66             if not os.path.isdir(filepath):67                 files.append(filepath if absolute_path else file)68         return files

一般用法如下:

1 traversal = FileTraversal("/home/user/testdir")2 traversal.setTopToDown(False).setErrorFunc(err_foo).setFollowLinks(True) #不設定,直接使用預設參數亦可3 files = traversal.getFiles()4 # do something with files ....

源檔案: FileTraversal.py

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.