提示:评论区扣1送工具
文章目录
- 前言
- 一、工具介绍
- 二、关键代码
- 三、下个版本优化
- 总结
前言
在日常开发和项目文档编写中,我们经常需要展示项目的目录结构。无论是编写技术文档、项目报告,还是进行团队协作,清晰展示目录树都是必不可少的。然而,手动编写目录树既繁琐又容易出错,特别是当项目庞大时。虽然操作系统自带tree命令,但功能有限,无法满足复杂的过滤需求,且在跨平台使用时存在差异。
一、工具介绍
基于以上情况,博主实现了这一个生成目录树结构的提效小工具,包含以下功能: 1、选择项目目录后自动生成目录树 2、自定义忽略版本控制目录、编译文件、日志等非必要内容 3、可设置目录遍历深度 4、支持不同风格的项目目录结构样式 5、生成后会显示统计信息和错误报告
二、关键代码
1、核心过滤算法使用多级分类策略,确保高效过滤
def generate_directory_tree(self, root_dir, ignore_hidden=True, ignore_patterns='',
prefix='', style='classic', smart_filter=True, max_depth=5):
# 构建忽略列表
ignore_list = []
# 添加默认过滤模式
ignore_list.extend([
'.git', '.svn', '.hg', '.vscode', '.idea',
'node_modules', 'dist', 'build', 'venv',
'__pycache__', '*.pyc', '*.log', '.DS_Store'
])
# 添加用户自定义忽略模式
if ignore_patterns:
patterns = [p.strip() for p in ignore_patterns.split(',') if p.strip()]
ignore_list.extend(patterns)
# 智能识别常见文件类型
if smart_filter:
ignore_list.extend([
'*.ini', '*.cfg', '*.json', '*.xml', '*.yml',
'*.jpg', '*.png', '*.gif', '*.mp3', '*.mp4',
'*.pdf', '*.docx', '*.xlsx', '*.pptx'
])
# 应用过滤规则
filtered = []
for entry in os.listdir(current_dir):
if ignore_hidden and entry.startswith('.'):
continue
skip = False
for pattern in ignore_list:
if fnmatch.fnmatch(entry, pattern) or pattern == entry:
skip = True
break
if not skip:
filtered.append(entry)
2、目录树生成算法:递归遍历目录结构,同时应用样式和深度控制
def traverse_dir(current_dir, current_prefix, current_depth):
if current_depth > max_depth:
return
try:
entries = os.listdir(current_dir)
except PermissionError:
return
# 分离目录和文件并排序
dirs = [e for e in entries if os.path.isdir(os.path.join(current_dir, e))]
files = [e for e in entries if not os.path.isdir(os.path.join(current_dir, e))]
entries_sorted = sorted(dirs) + sorted(files)
for idx, entry in enumerate(entries_sorted):
is_last = (idx == len(entries_sorted)-1)
# 应用样式
if style == 'classic':
connector = '└── ' if is_last else '├── '
indent = ' ' if is_last else '│ '
else: # modern
connector = '◾ ' if is_last else '▸ '
indent = ' ' if is_last else '│ '
# 添加当前条目
lines.append(f"{current_prefix}{connector}{entry}")
# 递归处理子目录
if os.path.isdir(os.path.join(current_dir, entry)):
new_prefix = current_prefix + indent
traverse_dir(
os.path.join(current_dir, entry),
new_prefix,
current_depth + 1
)
3、可视化过滤配置界面,支持分类展示和一键操作
class FilterConfigDialog(QDialog):
def __init__(self, selected_filters, parent=None):
super().__init__(parent)
self.setWindowTitle("默认过滤配置")
self.setGeometry(300, 300, 900, 650)
# 分类过滤选项
default_filters = [
('版本控制', ['.git', '.svn', '.hg']),
('构建输出', ['node_modules', 'dist', 'build', 'out']),
('环境目录', ['venv', 'env', '.env']),
('IDE配置', ['.vscode', '.idea', '.vs']),
('编译文件', ['*.pyc', '__pycache__', '*.class']),
('系统文件', ['Thumbs.db', '.DS_Store']),
('日志文件', ['*.log', '*.bak', '*.tmp']),
('常见文件类型', [
'*.ini', '*.json', '*.xml', '*.yml',
'*.jpg', '*.png', '*.mp3', '*.mp4',
'*.pdf', '*.docx', '*.xlsx'
])
]
# 创建网格布局展示选项
grid_layout = QGridLayout()
row, col = 0, 0
for category, patterns in default_filters:
group_box = QGroupBox(category)
inner_layout = QVBoxLayout()
for pattern in patterns:
check = QCheckBox(pattern)
check.setChecked(pattern in selected_filters)
self.filter_checks[pattern] = check
inner_layout.addWidget(check)
group_box.setLayout(inner_layout)
grid_layout.addWidget(group_box, row, col)
col = (col + 1) % 3 # 每行3列
if col == 0:
row += 1
4、生成完成后提供相关的运行结果、统计信息或错误提示
def update_summary_display(self):
summary_text = []
summary_text.append(f"总条目数: {self.summary_info['total_entries']}")
if self.summary_info['max_entries_exceeded']:
summary_text.append("⚠️ 条目数超过限制,部分内容未显示")
if self.summary_info['depth_limit_exceeded']:
summary_text.append("⚠️ 有未显示的更深层级的目录")
if self.summary_info['errors']:
summary_text.append("\\n错误信息:")
for error in self.summary_info['errors']:
summary_text.append(f" • {error}")
else:
summary_text.append("✅ 执行完成,没有错误")
self.summary_edit.setPlainText("\\n".join(summary_text))
三、下个版本优化
现在是v1.0版本,后续会更新2.0版本 1、实现HTML可视化树形结构或者图像导出 2、当前对目录/文件的过滤还达不到比较理想的效果,需要优化 3、实现预设常用项目结构模板、自定义模板保存 4、…
总结
本文介绍了一个基于PyQt5开发的一键生成项目目录树的自制小工具,解决了手动编写目录树的繁琐问题。这个工具支持自定义过滤规则(如忽略版本控制目录、编译文件等)、设置遍历深度、多种目录样式选择,并能生成统计信息和错误报告。核心功能包括多级分类过滤算法、递归遍历目录结构、可视化配置界面等,适用于技术文档编写和团队协作场景,显著提升工作效率。
评论前必须登录!
注册