使用Python创建一个文件夹结构生成器
作者:winfredzhang
这篇文章主要为大家详细介绍了如何使用Python创建一个文件夹结构生成器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
在本文中,我们将探讨如何利用Python的wxPython库来创建一个图形用户界面(GUI)应用程序,该应用程序允许用户通过简单的文本输入来创建复杂的文件夹结构。这个程序将包括一个文本框用于输入文件夹结构描述,一个按钮来触发结构创建过程,以及一个目录选择器来指定目标文件夹。
全部代码
import wx import os import re class FolderStructureCreator(wx.Frame): def __init__(self, parent, title): super().__init__(parent, title=title, size=(600, 400)) # 创建面板 panel = wx.Panel(self) # 创建控件 self.memo = wx.TextCtrl(panel, style=wx.TE_MULTILINE, size=(500, 200), pos=(50, 50)) self.create_button = wx.Button(panel, label="创建", pos=(50, 270)) self.folder_picker = wx.DirPickerCtrl(panel, path="", size=(500, -1), pos=(50, 300)) # 绑定事件 self.create_button.Bind(wx.EVT_BUTTON, self.on_create) self.Show() def on_create(self, event): # 获取目标文件夹路径 target_folder = self.folder_picker.GetPath() if not target_folder: wx.MessageBox("请选择目标文件夹", "错误", wx.ICON_ERROR) return # 获取输入的文件夹结构描述 folder_structure = self.memo.GetValue() if not folder_structure: wx.MessageBox("请输入文件夹结构描述", "错误", wx.ICON_ERROR) return # 根据文件夹结构描述创建文件夹和文件 self.create_structure(target_folder, folder_structure) def create_structure(self, base_path, structure): lines = structure.splitlines() path_stack = [base_path] # 初始化路径栈 for line in lines: # 使用正则表达式移除符号 clean_line = re.sub(r'[├└│─]+', '', line).strip() # 跳过空行 if not clean_line: continue indent_level = len(line) - len(line.lstrip(' ')) # 计算缩进级别 while len(path_stack) > indent_level + 1: path_stack.pop() # 回退到正确的父路径 if clean_line.endswith('/'): # 创建文件夹 folder_name = clean_line.rstrip('/') new_folder_path = os.path.join(path_stack[-1], folder_name) if not os.path.exists(new_folder_path): os.makedirs(new_folder_path) path_stack.append(new_folder_path) elif '.' in clean_line: # 创建文件 file_name = clean_line new_file_path = os.path.join(path_stack[-1], file_name) try: with open(new_file_path, 'w') as f: f.write('') # 创建空文件 except PermissionError as e: wx.MessageBox(f"权限错误,无法创建文件:{new_file_path}\n{str(e)}", "错误", wx.ICON_ERROR) return wx.MessageBox("文件夹和文件创建完成", "成功", wx.ICON_INFORMATION) if __name__ == "__main__": app = wx.App(False) FolderStructureCreator(None, title="文件夹结构创建器") app.MainLoop()
步骤1:安装wxPython
首先,你需要在你的Python环境中安装wxPython库。你可以通过pip安装它:
pip install wxPython
步骤2:创建主窗口类
接下来,我们定义一个名为FolderStructureCreator的类,该类继承自wx.Frame。在这个类的构造函数中,我们设置窗口的大小和标题,并初始化各种控件(如文本框、按钮和目录选择器)。
import wx import os import re class FolderStructureCreator(wx.Frame): def __init__(self, parent, title): super().__init__(parent, title=title, size=(600, 400)) # 创建面板 panel = wx.Panel(self) # 创建控件 self.memo = wx.TextCtrl(panel, style=wx.TE_MULTILINE, size=(500, 200), pos=(50, 50)) self.create_button = wx.Button(panel, label="创建", pos=(50, 270)) self.folder_picker = wx.DirPickerCtrl(panel, path="", size=(500, -1), pos=(50, 300)) # 绑定事件 self.create_button.Bind(wx.EVT_BUTTON, self.on_create) self.Show()
步骤3:实现创建功能
在on_create方法中,我们获取用户输入的目标文件夹路径和文件夹结构描述,然后调用create_structure方法来实际创建文件夹和文件。
def on_create(self, event): target_folder = self.folder_picker.GetPath() if not target_folder: wx.MessageBox("请选择目标文件夹", "错误", wx.ICON_ERROR) return folder_structure = self.memo.GetValue() if not folder_structure: wx.MessageBox("请输入文件夹结构描述", "错误", wx.ICON_ERROR) return self.create_structure(target_folder, folder_structure)
步骤4:解析文件夹结构描述并创建文件夹/文件
create_structure方法负责解析用户输入的文件夹结构描述,并根据这些信息在指定的基路径下创建相应的文件夹和文件。
def create_structure(self, base_path, structure): lines = structure.splitlines() path_stack = [base_path] for line in lines: clean_line = re.sub(r'[├└│─]+', '', line).strip() if not clean_line: continue indent_level = len(line) - len(line.lstrip(' ')) while len(path_stack) > indent_level + 1: path_stack.pop() if clean_line.endswith('/'): folder_name = clean_line.rstrip('/') new_folder_path = os.path.join(path_stack[-1], folder_name) if not os.path.exists(new_folder_path): os.makedirs(new_folder_path) path_stack.append(new_folder_path) elif '.' in clean_line: file_name = clean_line new_file_path = os.path.join(path_stack[-1], file_name) try: with open(new_file_path, 'w') as f: f.write('') except PermissionError: wx.MessageBox("权限不足,无法创建文件", "错误", wx.ICON_ERROR)
运行结果
以上就是如何使用Python和wxPython创建一个文件夹结构生成器的完整指南。这个工具可以大大简化在文件系统中组织和管理文件的过程,特别是对于需要快速建立复杂文件夹结构的开发人员来说非常有用。
到此这篇关于使用Python创建一个文件夹结构生成器的文章就介绍到这了,更多相关Python创建文件夹结构生成器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!