python 3.6 脚本 : 获取指定文件夹下面的所有文件

#!/usr/bin/python3
# -*- coding:utf-8 -*-
from pathlib import Path

"""获得所有子文件夹下文件路径的工厂方法"""


class PathsFactory:
    """初始化方法"""
    _file_paths = []

    def __init__(self, parent_path):
        self._parent_path = parent_path

    """获得父节点"""

    def get_parent_path(self):
        return self._parent_path

    """静态方法:看输入路径是否是一个目录"""

    @staticmethod
    def isdir(path):
        p = Path(path)
        return p.is_dir()

    """外部接口方法。如果有文件,返回文件集合,没有的话返回False"""

    def get_file_paths(self):
        if self.isdir(self._parent_path):
            return self._get_all_file_paths(self._parent_path)
        else:
            return []

    """内部方法,用于获取所有路径"""

    def _get_all_file_paths(self, parent_dir_path):
        temp_paths = []
        try:
            temp_paths = self._get_all_child_paths(parent_dir_path)
        except PermissionError as e:
            print(e)
        except FileNotFoundError as e:
            print(e)
        for temp_path in temp_paths:
            if self.isdir(temp_path):
                self._get_all_file_paths(temp_path)
            else:
                self._file_paths.append(Path(temp_path))
        return self._file_paths

    """通过传入父文件路径,获得所有子文件,包括文件夹路径名"""

    @staticmethod
    def _get_all_child_paths(parent_dir_path):
        child_paths = []
        parent_path = Path(parent_dir_path)
        child_path_iter = parent_path.iterdir()
        for child_path in child_path_iter:
            child_paths.append(child_path)
        return child_paths


pa = PathsFactory("F:")
file_path = pa.get_file_paths()

捎带上一个解压文件夹里面的所有。zip文件

import zipfile
import re
from demo import PathsFactory

path = 'F:\大数据\\200套后台响应式模板【kk梦空间】'
path_factory = PathsFactory(path)
file_paths = path_factory.get_file_paths()


def un_zip_file(str_file_name):
    filename = str_file_name
    filedir = str_file_name.replace('.zip', '')  # 解压后放入的目录
    r = zipfile.is_zipfile(filename)
    if r:
        fz = zipfile.ZipFile(filename, 'r')
        for file in fz.namelist():
            fz.extract(file, filedir)


for file_path in file_paths:
    pattern = re.compile('.*\.zip')
    str_file_name = str(file_path)
    match = pattern.match(str_file_name)
    if match is not None:
        try:
            un_zip_file(str_file_name)
        except Exception as e:
            print(e)

 

转载于:https://my.oschina.net/marjeylee/blog/875343

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值