Python制作可视化GUI界面,一键实现自动分类管理文件!

【Python制作可视化GUI界面,一键实现自动分类管理文件!】经常杂乱无章的文件夹会让我们找不到所想要的文件,因此特意制作了一个可视化GUI界面,通过输入路径一键点击实现文件分门别类的归档。
不同的文件后缀归类为不同的类别
我们先罗列一下大致有几类文件,根据文件的后缀来设定,大致如下

SUBDIR = { "DOCUMENTS": [".pdf", ".docx", ".txt", ".html"], "AUDIO": [".m4a", ".m4b", ".mp3", ".mp4"], "IMAGES": [".jpg", ".jpeg", ".png", ".gif"], "DataFile": [".csv", ".xlsx"] }

上面所罗列出来的文件后缀并不全面,读者可以根据自己的需求往里面添加,可以根据自己的喜好来进行分文别类,然后我们自定义一个函数,根据输入的一个文件后缀来判断它是属于哪个类的
def pickDir(value): for category, ekstensi in SUBDIR.items(): for suffix in ekstensi: if suffix == value: return category

例如输入的是.pdf返回的则是DOCUMENTS这个类。我们还需要再自定义一个函数,遍历当前目录下的所有文件,获取众多文件的后缀,将这些不同后缀的文件分别移入不同类别的文件夹,代码如下
def organizeDir(path_val):for item in os.scandir(path_val): if item.is_dir(): continuefilePath = Path(item) file_suffix = filePath.suffix.lower() directory = pickDir(file_suffix) directoryPath = Path(directory) # 新建文件夹,要是该文件夹不存在的话 if directoryPath.is_dir() != True: directoryPath.mkdir() filePath.rename(directoryPath.joinpath(filePath))

output
Python制作可视化GUI界面,一键实现自动分类管理文件!
文章图片

我们再次基础之上,再封装一下做成Python可视化GUI界面,代码如下
class FileOrgnizer(QWidget): def __init__(self): super().__init__() self.lb = QLabel(self) self.lb.setGeometry(70, 25, 80, 40) self.lb.setText('文件夹整理助手:') self.textbox = QLineEdit(self) self.textbox.setGeometry(170, 30, 130, 30) self.findButton = QPushButton('整理', self) self.findButton.setGeometry(60, 85, 100, 40) self.quitButton = QPushButton('退出', self) self.quitButton.clicked.connect(self.closeEvent) self.findButton.clicked.connect(self.organizeDir) self.quitButton.setGeometry(190, 85, 100, 40) self.setGeometry(500, 500, 350, 150) self.setWindowTitle('Icon') self.setWindowIcon(QIcon('../751.png')) self.show()def pickDir(self, value): for category, ekstensi in SUBDIR.items(): for suffix in ekstensi: if suffix == value: return categorydef organizeDir(self, event):path_val = self.textbox.text() print("路径为: " + path_val) for item in os.scandir(path_val): if item.is_dir(): continuefilePath = Path(item) fileType = filePath.suffix.lower() directory = self.pickDir(fileType) if directory == None: continuedirectoryPath = Path(directory) if directoryPath.is_dir() != True: directoryPath.mkdir() filePath.rename(directoryPath.joinpath(filePath)) reply = QMessageBox.information(self, "完成", "任务完成,请问是否要退出?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: event.accept() else: event.ignore()def closeEvent(self, event): reply = QMessageBox.question(self, '退出', "确定退出?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: event.accept() else: event.ignore()

效果如下图所示
Python制作可视化GUI界面,一键实现自动分类管理文件!
文章图片

最后我们通过pyinstaller模块来将Python代码打包成可执行文件,操作指令如下
pyinstaller -F -w 文件名.py

部分参数含义如下:
  • -F:表示生成单个可执行文件
  • -w:表示去掉控制台窗口,这在GUI界面时时非常有用的
  • -i:表示可执行文件的图标
以上就是本次分享的所有内容,如果你觉得文章还不错,欢迎关注公众号:Python编程学习圈,每日干货分享,发送“J”还可领取大量学习资料,内容覆盖Python电子书、教程、数据库编程、Django,爬虫,云计算等等。或是前往编程学习网,了解更多编程技术知识。

    推荐阅读