#!/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)