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)

猜你喜欢

转载自www.cnblogs.com/yocichen/p/11693240.html
今日推荐