引言:
在日常使用计算机时,我们经常会在桌面上保存各种类型的文件,例如文档、图片、音频和视频等。然而,随着时间的推移,桌面上的文件可能会变得杂乱无章,给文件查找和管理带来困难。为了解决这个问题,我们可以使用Python编写一个文件分析器,它可以帮助我们整理桌面上的文件,并提供文件类型的可视化统计。
本文将介绍如何使用Python编写一个桌面文件分析器,它可以分析指定文件夹中的文件,并将文件按照类型进行整理。同时,我们还将使用数据可视化技术创建饼图,展示每种文件类型的数量占比。
C:\pythoncode\new\desktopfiletypevisuallizetion.py
准备工作
在开始之前,我们需要安装Python和一些必要的库。请确保您已经安装了Python,并使用pip
命令安装以下库:
pip install wxPython matplotlib
全部代码
import os
import shutil
import wx
import sqlite3
import matplotlib.pyplot as plt
class DatabaseManager:
def __init__(self, db_name):
self.conn = sqlite3.connect(db_name)
self.cursor = self.conn.cursor()
self.create_table()
def create_table(self):
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS file_info (
id INTEGER PRIMARY KEY AUTOINCREMENT,
file_type TEXT,
file_date TEXT,
file_size INTEGER,
file_name TEXT,
file_path TEXT
)
''')
self.conn.commit()
def insert_file_info(self, file_type, file_date, file_size, file_name, file_path):
self.cursor.execute('''
INSERT INTO file_info (file_type, file_date, file_size, file_name, file_path)
VALUES (?, ?, ?, ?, ?)
''', (file_type, file_date, file_size, file_name, file_path))
self.conn.commit()
def clear_table(self):
self.cursor.execute('DELETE FROM file_info')
self.conn.commit()
def get_file_types(self):
self.cursor.execute('SELECT DISTINCT file_type FROM file_info')
return self.cursor.fetchall()
def get_file_info(self):
self.cursor.execute('SELECT file_name, file_type, file_path FROM file_info')
return self.cursor.fetchall()
def get_file_stats(self):
self.cursor.execute('''
SELECT file_type, COUNT(*) AS count, SUM(file_size) AS size FROM file_info
GROUP BY file_type
''')
return self.cursor.fetchall()
def close(self):
self.cursor.close()
self.conn.close()
class FileAnalyzer(wx.Frame):
def __init__(self, parent, title):
super(FileAnalyzer, self).__init__(parent, title=title, size=(400, 400))
self.db_manager = DatabaseManager('file_info.db')
self.InitUI()
def InitUI(self):
panel = wx.Panel(self)
vbox = wx.BoxSizer(wx.VERTICAL)
self.dir_picker = wx.DirPickerCtrl(panel, message="选择文件夹", style=wx.DIRP_USE_TEXTCTRL)
vbox.Add(self.dir_picker, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
analyze_button = wx.Button(panel, label='开始分析')
analyze_button.Bind(wx.EVT_BUTTON, self.analyze_files)
vbox.Add(analyze_button, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
organize_button = wx.Button(panel, label='整理文件')
organize_button.Bind(wx.EVT_BUTTON, self.organize_files)
vbox.Add(organize_button, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
show_chart_button = wx.Button(panel, label='显示饼图')
show_chart_button.Bind(wx.EVT_BUTTON, self.show_pie_chart)
vbox.Add(show_chart_button, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
panel.SetSizer(vbox)
self.Show()
def analyze_files(self, event):
folder_path = self.dir_picker.GetPath()
if not folder_path:
wx.MessageBox("请选择一个文件夹!", "提示", wx.OK | wx.ICON_INFORMATION)
return
try:
self.db_manager.clear_table()
for root, dirs, files in os.walk(folder_path):
for file_name in files:
file_path = os.path.join(root, file_name)
file_type = os.path.splitext(file_name)[1]
file_date = os.path.getctime(file_path)
file_size = os.path.getsize(file_path)
self.db_manager.insert_file_info(file_type, file_date, file_size, file_name, file_path)
wx.MessageBox("分析完成!", "提示", wx.OK | wx.ICON_INFORMATION)
except Exception as e:
wx.MessageBox(f"分析过程中出现错误:{str(e)}", "错误", wx.OK | wx.ICON_ERROR)
def organize_files(self, event):
folder_path = self.dir_picker.GetPath()
if not folder_path:
wx.MessageBox("请选择一个文件夹!", "提示", wx.OK | wx.ICON_INFORMATION)
return
try:
manager_folder = os.path.join(folder_path, 'manager')
if not os.path.exists(manager_folder):
os.mkdir(manager_folder)
for file_type in self.db_manager.get_file_types():
file_type_folder = os.path.join(manager_folder, file_type[0] if file_type[0] else 'No_Extension')
if not os.path.exists(file_type_folder):
os.mkdir(file_type_folder)
for file_name, file_type, file_path in self.db_manager.get_file_info():
destination_folder = os.path.join(manager_folder, file_type if file_type else 'No_Extension')
destination_path = os.path.join(destination_folder, file_name)
if os.path.exists(file_path): # 检查源文件是否存在
if os.path.exists(destination_path):
base, extension = os.path.splitext(file_name)
counter = 1
while os.path.exists(destination_path):
new_file_name = f"{base}_{counter}{extension}"
destination_path = os.path.join(destination_folder, new_file_name)
counter += 1
shutil.copy2(file_path, destination_path)
else:
print(f"文件不存在:{file_path}")
wx.MessageBox("文件整理完成!", "提示", wx.OK | wx.ICON_INFORMATION)
except Exception as e:
wx.MessageBox(f"整理文件时出现错误:{str(e)}", "错误", wx.OK | wx.ICON_ERROR)
def show_pie_chart(self, event):
try:
result = self.db_manager.get_file_stats()
file_types = [row[0] if row[0] else 'No_Extension' for row in result]
counts = [row[1] for row in result]
plt.figure(figsize=(10, 8))
plt.pie(counts, labels=file_types, autopct='%1.1f%%')
plt.axis('equal')
plt.title('File Type Distribution')
plt.savefig('pie_chart.png')
plt.close()
wx.MessageBox("饼图已保存为 pie_chart.png!", "提示", wx.OK | wx.ICON_INFORMATION)
if os.path.exists('pie_chart.png'):
os.startfile('pie_chart.png')
except Exception as e:
wx.MessageBox(f"生成饼图时出现错误:{str(e)}", "错误", wx.OK | wx.ICON_ERROR)
def __del__(self):
self.db_manager.close()
if __name__ == '__main__':
app = wx.App()
frame = FileAnalyzer(None, title='文件分析器')
app.MainLoop()
文件分析器
首先,我们将创建一个基于wxPython
库的简单图形用户界面(GUI),用于选择文件夹和执行文件分析操作。以下是完整的Python代码:
def analyze_files(self, event):
folder_path = self.dir_picker.GetPath()
if not folder_path:
wx.MessageBox("请选择一个文件夹!", "提示", wx.OK | wx.ICON_INFORMATION)
return
try:
self.db_manager.clear_table()
for root, dirs, files in os.walk(folder_path):
for file_name in files:
file_path = os.path.join(root, file_name)
file_type = os.path.splitext(file_name)[1]
file_date = os.path.getctime(file_path)
file_size = os.path.getsize(file_path)
self.db_manager.insert_file_info(file_type, file_date, file_size, file_name, file_path)
wx.MessageBox("分析完成!", "提示", wx.OK | wx.ICON_INFORMATION)
except Exception as e:
wx.MessageBox(f"分析过程中出现错误:{str(e)}", "错误", wx.OK | wx.ICON_ERROR)
在这段代码中,我们使用wxPython
库创建了一个窗口,其中包含三个按钮:选择文件夹、开始分析和整理文件。用户可以通过选择文件夹按钮选择要分析的文件夹。点击开始分析按钮后,程序将遍历文件夹中的文件,并将文件的类型、日期、大小、名称和路径等信息存储到SQLite数据库中。
点击整理文件按钮后,程序将根据文件类型创建相应的文件夹,并将文件复制到相应的文件夹中。
数据可视化
为了更直观地了解文件类型的占比情况,我们将使用matplotlib
库创建一个饼图。以下是完整的Python代码:
def show_pie_chart(self, event):
try:
result = self.db_manager.get_file_stats()
file_types = [row[0] if row[0] else 'No_Extension' for row in result]
counts = [row[1] for row in result]
plt.figure(figsize=(10, 8))
plt.pie(counts, labels=file_types, autopct='%1.1f%%')
plt.axis('equal')
plt.title('File Type Distribution')
plt.savefig('pie_chart.png')
plt.close()
wx.MessageBox("饼图已保存为 pie_chart.png!", "提示", wx.OK | wx.ICON_INFORMATION)
if os.path.exists('pie_chart.png'):
os.startfile('pie_chart.png')
except Exception as e:
wx.MessageBox(f"生成饼图时出现错误:{str(e)}", "错误", wx.OK | wx.ICON_ERROR)
在这段代码中,我们从SQLite数据库中查询文件类型的数量或大小占比。然后,使用matplotlib
库绘制饼图,并将饼图保存为图像文件。最后,如果图像文件存在,将打开图像文件以供查看。
结果如下
结论
通过使用Python编写的文件分析器,我们可以方便地整理桌面上的文件,并可视化文件类型的占比情况。这个工具不仅可以提高文件管理的效率,还可以让我们更清晰地了解文件的组成和分布情况。