Python文件管理器开发之文件遍历与文档预览功能实现教程
项目概述
我们开发的文件管理器具备以下核心功能:
- 文件夹选择与子目录遍历
- 文件列表显示与管理
- Word和Excel文档内容预览
- WPS Office集成打开功能
核心功能实现详解
1. 文件夹遍历功能
文件夹遍历是文件管理器的基础功能,我们采用了分层遍历的设计思路。
1.1 主文件夹加载
def load_subfolders(self):
"""加载子文件夹到listbox1"""
self.listbox1.Clear()
self.listbox2.Clear()
self.preview_text.Clear()
if not self.current_folder or not os.path.exists(self.current_folder):
self.status_bar.SetStatusText("无效的文件夹路径")
return
try:
subfolders = []
files = []
# 遍历当前文件夹中的所有项目
for item in os.listdir(self.current_folder):
item_path = os.path.join(self.current_folder, item)
if os.path.isdir(item_path):
subfolders.append(item)
elif os.path.isfile(item_path):
files.append(item)
# 排序并添加到列表
subfolders.sort()
for folder in subfolders:
self.listbox1.Append(folder)
# 处理特殊情况:没有子文件夹但有文件
if not subfolders and files:
files.sort()
for file_name in files:
self.listbox2.Append(file_name)
self.status_bar.SetStatusText(f"当前文件夹: 0 个子文件夹, {len(files)} 个文件")
else:
self.status_bar.SetStatusText(f"当前文件夹: {len(subfolders)} 个子文件夹, {len(files)} 个文件")
except PermissionError:
wx.MessageBox("没有权限访问此文件夹", "错误", wx.OK | wx.ICON_ERROR)
self.status_bar.SetStatusText("权限错误")
except Exception as e:
wx.MessageBox(f"读取文件夹时出错:\n{str(e)}", "错误", wx.OK | wx.ICON_ERROR)
self.status_bar.SetStatusText(f"读取错误: {str(e)}")
核心技术点解析:
- 路径验证:使用
os.path.exists()确保路径有效 - 类型识别:通过
os.path.isdir()和os.path.isfile()区分文件夹和文件 - 异常处理:捕获权限错误和其他异常,提供用户友好的错误提示
- 智能显示:当没有子文件夹时,直接显示当前目录下的文件
1.2 文件列表加载
def load_files(self, folder_path):
"""加载文件到listbox2"""
self.listbox2.Clear()
if not os.path.exists(folder_path):
return
try:
files = []
for item in os.listdir(folder_path):
item_path = os.path.join(folder_path, item)
if os.path.isfile(item_path):
files.append(item)
# 排序文件列表
files.sort()
for file_name in files:
self.listbox2.Append(file_name)
self.status_bar.SetStatusText(f"找到 {len(files)} 个文件")
except PermissionError:
wx.MessageBox("没有权限访问此文件夹", "错误", wx.OK | wx.ICON_ERROR)
这里的关键是过滤机制,只获取文件而忽略子目录,确保文件列表的纯净性。
2. 文档预览功能实现
文档预览是本项目的亮点功能,支持多种文档格式的内容展示。
2.1 预览分发器
def preview_file(self, file_path):
"""预览文件内容"""
self.preview_text.Clear()
if not os.path.exists(file_path):
self.preview_text.SetValue("文件不存在")
return
file_ext = Path(file_path).suffix.lower()
try:
if file_ext == '.docx':
self.preview_docx(file_path)
elif file_ext == '.doc':
self.preview_doc(file_path)
elif file_ext in ['.xlsx', '.xls']:
self.preview_excel(file_path)
else:
self.preview_text.SetValue(f"不支持预览此文件类型: {file_ext}\n\n支持的文件类型:\n- Word文档 (.docx, .doc)\n- Excel文件 (.xlsx, .xls)")
except Exception as e:
self.preview_text.SetValue(f"预览文件时出错:\n{str(e)}")
设计模式:采用了策略模式,根据文件扩展名选择相应的预览策略。
2.2 Word文档预览实现
现代Word文档(.docx)预览
def preview_docx(self, file_path):
"""预览Word文档"""
try:
doc = Document(file_path)
content = []
content.append(f"文档: {os.path.basename(file_path)}")
content.append("=" * 50)
# 读取段落内容
for i, paragraph in enumerate(doc.paragraphs):
if paragraph.text.strip():
content.append(f"段落 {i+1}: {paragraph.text}")
# 读取表格内容
if doc.tables:
content.append("\n" + "=" * 30 + " 表格内容 " + "=" * 30)
for table_idx, table in enumerate(doc.tables):
content.append(f"\n表格 {table_idx + 1}:")
for row_idx, row in enumerate(table.rows):
row_data = []
for cell in row.cells:
row_data.append(cell.text.strip())
content.append(f" 行 {row_idx + 1}: {' | '.join(row_data)}")
self.preview_text.SetValue("\n".join(content))
self.status_bar.SetStatusText(f"已预览Word文档: {os.path.basename(file_path)}")
except Exception as e:
self.preview_text.SetValue(f"无法预览Word文档:\n{str(e)}\n\n请确保安装了 python-docx 库")
技术亮点:
- 使用
python-docx库解析DOCX格式 - 分别处理段落和表格内容
- 结构化展示,便于阅读
传统Word文档(.doc)预览
def preview_doc(self, file_path):
"""预览老式Word文档(.doc)"""
try:
# 方法1: 使用 docx2txt
try:
import docx2txt
text_content = docx2txt.process(file_path)
if text_content and text_content.strip():
content = []
content.append(f"Word文档: {os.path.basename(file_path)}")
content.append("=" * 50)
content.append("注意: 这是.doc格式文档的文本内容预览")
content.append("=" * 50)
content.append(text_content)
self.preview_text.SetValue("\n".join(content))
self.status_bar.SetStatusText(f"已预览Word文档(.doc): {os.path.basename(file_path)}")
return
except ImportError:
pass
# 方法2: 使用 win32com
try:
import win32com.client as win32
word_app = win32.Dispatch('Word.Application')
word_app.Visible = False
try:
doc = word_app.Documents.Open(file_path)
text_content = doc.Content.Text
paragraph_count = doc.Paragraphs.Count
table_count = doc.Tables.Count
content = []
content.append(f"Word文档: {os.path.basename(file_path)}")
content.append("=" * 50)
content.append(f"段落数量: {paragraph_count}")
content.append(f"表格数量: {table_count}")
content.append("=" * 50)
content.append("文档内容:")
content.append(text_content[:5000]) # 限制字符数
doc.Close()
self.preview_text.SetValue("\n".join(content))
return
finally:
word_app.Quit()
except ImportError:
pass
# 降级处理:显示安装指导
self.preview_text.SetValue(
f"无法预览 .doc 格式文档: {os.path.basename(file_path)}\n\n"
"要预览 .doc 文件,请安装以下任一依赖库:\n\n"
"方法1 (推荐): pip install docx2txt\n"
"方法2: pip install mammoth\n"
"方法3 (Windows): pip install pywin32\n\n"
)
except Exception as e:
self.preview_text.SetValue(f"预览.doc文档时出错:\n{str(e)}")
多重策略设计:
- docx2txt:轻量级文本提取
- mammoth:更好的格式保持
- win32com:利用系统Word程序,功能最全
- 降级处理:提供详细的安装指导
2.3 Excel文件预览
def preview_excel(self, file_path):
"""预览Excel文件"""
try:
excel_file = pd.ExcelFile(file_path)
content = []
content.append(f"Excel文件: {os.path.basename(file_path)}")
content.append("=" * 50)
content.append(f"工作表数量: {len(excel_file.sheet_names)}")
content.append(f"工作表名称: {', '.join(excel_file.sheet_names)}")
content.append("")
# 预览每个工作表的前几行
for sheet_name in excel_file.sheet_names:
content.append("=" * 30 + f" {sheet_name} " + "=" * 30)
try:
df = pd.read_excel(file_path, sheet_name=sheet_name, nrows=10)
content.append(f"行数: {len(df)}, 列数: {len(df.columns)}")
content.append(f"列名: {', '.join(df.columns.astype(str))}")
content.append("")
content.append("前10行数据:")
content.append(df.to_string(index=False, max_rows=10))
content.append("")
except Exception as e:
content.append(f"无法读取工作表 {sheet_name}: {str(e)}")
self.preview_text.SetValue("\n".join(content))
except Exception as e:
self.preview_text.SetValue(f"无法预览Excel文件:\n{str(e)}")
Excel处理特色:
- 使用pandas处理Excel文件
- 展示工作表结构信息
- 限制数据行数避免界面卡顿
- 逐个工作表预览
运行结果

到此这篇关于Python文件管理器开发之文件遍历与文档预览功能实现教程的文章就介绍到这了,更多相关Python文件管理器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Python输出由1,2,3,4组成的互不相同且无重复的三位数
这篇文章主要介绍了Python输出由1,2,3,4组成的互不相同且无重复的三位数,分享了相关代码示例,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下2018-02-02
django框架基于queryset和双下划线的跨表查询操作详解
这篇文章主要介绍了django框架基于queryset和双下划线的跨表查询操作,结合实例形式详细分析了Django框架queryset和双下划线的跨表查询相关实现技巧与操作注意事项,需要的朋友可以参考下2019-12-12
Python中Collections模块的Counter容器类使用教程
Counter是Python标准库提供的一个非常有用的容器,可以用来对序列中出现的各个元素进行计数,下面就来一起看一下Python中Collections模块的Counter容器类使用教程2016-05-05
python连接并简单操作SQL server数据库详细步骤
python作为一门十分火热的编程语言,操作数据库自然是必不可少的,下面这篇文章主要给大家介绍了关于python连接并简单操作SQL server数据库的相关资料,需要的朋友可以参考下2023-06-06


最新评论