首页 > 编程语言 > 详细

python 提取目录中特定类型的文件

时间:2019-10-20 14:21:42      阅读:118      评论:0      收藏:0      [点我收藏+]

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)

python 提取目录中特定类型的文件

原文:https://www.cnblogs.com/yocichen/p/11693240.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!