# -*- coding:utf-8 -*- """ author: Zoupers create: 2019/10/7 18:13 file name: packer description: 为了使某个项目的附属文件全部集中在一个文件夹中而使用的一个类 """ import os from typing import Union class Home: def __init__(self, name, path=None, construction=None): self.home_name = name # 家目录名字 if path: self.home_path = os.path.join(path, name) else: self.home_path = name if not os.path.exists(name): os.mkdir(name) else: print("该目录已存在!") def open(self, path, *args, **kwargs): document_path = os.path.join(self.home_path, path) return open(document_path, *args, **kwargs) @staticmethod def mkdir(dir_path): print("开始创建目录 %s" % dir_path) if not os.path.exists(dir_path): os.mkdir(dir_path) print("成功创建目录 %s" % dir_path) else: print("该目录已存在!") @staticmethod def mkfile(file_path): print("开始创建文件 %s" % file_path) if not os.path.exists(file_path): f = open(file_path, "w", encoding='utf8') f.close() print("成功创建文件 %s" % file_path) else: print("该文件已存在!") def _construct(self, construction: Union[list, dict, tuple], home_path=None): """ 根据json格式创建文件树 :param construction: :return: """ home_path = self.home_path if not home_path else home_path if isinstance(construction, str): self.mkdir(os.path.join(home_path, construction)) elif isinstance(construction, list): for items in construction: self._construct(items, home_path) elif isinstance(construction, dict): for root, sub in list(construction.items()): self.mkdir(os.path.join(home_path, root)) self._construct(construction=sub, home_path=os.path.join(home_path, root)) elif isinstance(construction, tuple): for file in construction: self.mkfile(os.path.join(home_path, file)) def construct(self, *args, **kwargs): return self._construct(*args, **kwargs) if __name__ == '__main__': print("初始化变量") tree = [('index.html',), {'js': ('index.js',)}, {'css': ('style.css', 'reset.css')}] dic_root = Home("Hello") print("初始化变量完毕,开始构建文件树") dic_root.construct(tree) print("程序执行完毕")