python 提取目錄中特定類型的文件


python使用‘os’和‘re’模塊提取目錄中特定類型的文件,這兩個模都是安裝python自帶的,所以不需要安裝。

思路:

使用os庫lilstdir獲取文件夾中的所有文件名,然后帶上文件夾路徑組合成為完整絕對路徑,然后去判斷該路徑文件的類型,如果是文件,使用re庫正則相關函數去篩選出特定后綴的文件;如果是文件夾,遞歸處理此文件夾。

注意:

下面代碼提取的是‘xlsx’文件,如果需要提取其他類型的文件,替換re.complie('str')中的正則表達式即可。

源碼:

import os
import re

fileList = []

# Function can get *.xls/*.xlsx file from the directory
"""
dirpath: str, the path of the directory
"""
def _getfiles(dirPath):
    # open directory 
    files = os.listdir(dirPath)
    # re match *.xls/xlsx,you can change 'xlsx' to 'doc' or other file types.
    ptn = re.compile('.*\.xlsx')
    for f in files:
        # isdir, call self
        if (os.path.isdir(dirPath + '\\' + f)):
            getfiles(dirPath + '\\' + f)
        # isfile, judge
        elif (os.path.isfile(dirPath + '\\' + f)):
            res = ptn.match(f)
            if (res != None):
                fileList.append(dirPath + '\\' + res.group())
        else:
            fileList.append(dirPath + '\\無效文件')


# Function called outside
"""
dirpath: str, the path of the directory
"""
def getfiles(dirPath):
    _getfiles(dirPath)
    return fileList

if __name__ == "__main__":
     path = 'D:\\pyfiles\\test'
     res = getfiles(path)
     print('提取結果:')
     for f in res:
         print(f)


免責聲明!

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



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