Python——批量修改文件名

  •  2019-05-20 15:50:13
  •  216
  •  0

用Python+PyQT5做的批量修改文件名程序

  • 1 安装相关模块

pip install pyqt5
  • 2 导入相关模块

from PyQt5 import QtCore, QtGui, QtWidgets, Qt
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QTimer, QDateTime
import re, os
import PyQt5.sip
import resource
import time
  • 3 构建GUI界面

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(598, 447)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
        MainWindow.setSizePolicy(sizePolicy)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/logo.png"), QtGui.QIcon.Normal, QtGui.QIcon.On)
        MainWindow.setWindowIcon(icon)
        MainWindow.setWindowOpacity(1.0)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setObjectName("verticalLayout")
        self.gridLayout_2 = QtWidgets.QGridLayout()
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.gridLayout = QtWidgets.QGridLayout()
        self.gridLayout.setObjectName("gridLayout")
        self.old_list = QtWidgets.QListWidget(self.centralwidget)
        self.old_list.setObjectName("old_list")
        self.gridLayout.addWidget(self.old_list, 1, 0, 1, 1)
        self.new_label = QtWidgets.QLabel(self.centralwidget)
        font = QtGui.QFont()
        font.setFamily("宋体")
        font.setPointSize(9)
        self.new_label.setFont(font)
        self.new_label.setObjectName("new_label")
        self.gridLayout.addWidget(self.new_label, 0, 1, 1, 1)
        self.new_list = QtWidgets.QListWidget(self.centralwidget)
        self.new_list.setObjectName("new_list")
        self.gridLayout.addWidget(self.new_list, 1, 1, 1, 1)
        self.old_label = QtWidgets.QLabel(self.centralwidget)
        font = QtGui.QFont()
        font.setFamily("宋体")
        font.setPointSize(9)
        self.old_label.setFont(font)
        self.old_label.setObjectName("old_label")
        self.gridLayout.addWidget(self.old_label, 0, 0, 1, 1)
        self.gridLayout_2.addLayout(self.gridLayout, 1, 0, 1, 3)
        self.confirm_btn = QtWidgets.QPushButton(self.centralwidget)
        self.confirm_btn.setObjectName("confirm_btn")
        self.confirm_btn.clicked.connect(self.create_new_file_name_list)
        self.gridLayout_2.addWidget(self.confirm_btn, 0, 2, 1, 1)
        self.first_name_label = QtWidgets.QLabel(self.centralwidget)
        self.first_name_label.setObjectName("first_name_label")
        self.gridLayout_2.addWidget(self.first_name_label, 0, 0, 1, 1)
        self.first_name_input = QtWidgets.QLineEdit(self.centralwidget)
        self.first_name_input.setObjectName("first_name_input")
        self.gridLayout_2.addWidget(self.first_name_input, 0, 1, 1, 1)
        self.verticalLayout.addLayout(self.gridLayout_2)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 598, 23))
        self.menubar.setObjectName("menubar")
        self.menu = QtWidgets.QMenu(self.menubar)
        self.menu.setObjectName("menu")
        self.menu_2 = QtWidgets.QMenu(self.menubar)
        self.menu_2.setObjectName("menu_2")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.actiondakai = QtWidgets.QAction(MainWindow)
        self.actiondakai.setObjectName("actiondakai")
        self.actiondakai.triggered.connect(self.openfile)

        self.actionxiugai = QtWidgets.QAction(MainWindow)
        self.actionclear = QtWidgets.QAction(MainWindow)
        self.actionclear.setObjectName("actionclear")
        self.actionclear.triggered.connect(self.clear_data)

        self.actionxiugai.setObjectName("actionxiugai")
        self.actionxiugai.triggered.connect(self.re_name)

        self.actiontuichu = QtWidgets.QAction(MainWindow)
        self.actiontuichu.setShortcutContext(QtCore.Qt.WindowShortcut)
        self.actiontuichu.setObjectName("actiontuichu")

        self.actionshiyong = QtWidgets.QAction(MainWindow)
        self.actionshiyong.setObjectName("actionshiyong")
        self.actionshiyong.triggered.connect(self.help)

        self.actionguanyu = QtWidgets.QAction(MainWindow)
        self.actionguanyu.setObjectName("actionguanyu")
        self.actionguanyu.triggered.connect(self.about)

        self.actionlianxizuozhe = QtWidgets.QAction(MainWindow)
        self.actionlianxizuozhe.setObjectName("actionlianxizuozhe")
        self.actionlianxizuozhe.triggered.connect(self.contact_me)

        self.menu.addAction(self.actiondakai)
        self.menu.addAction(self.actionxiugai)
        self.menu.addAction(self.actionclear)
        self.menu.addSeparator()
        self.menu.addAction(self.actiontuichu)
        self.menu_2.addAction(self.actionshiyong)
        self.menu_2.addAction(self.actionguanyu)
        self.menu_2.addSeparator()
        self.menu_2.addAction(self.actionlianxizuozhe)
        self.menubar.addAction(self.menu.menuAction())
        self.menubar.addAction(self.menu_2.menuAction())

        self.retranslateUi(MainWindow)
        self.actiontuichu.triggered.connect(MainWindow.close)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        MainWindow.setTabOrder(self.old_list, self.new_list)

        self.timer = QTimer()
        self.timer.start(1000)
        self.timer.timeout.connect(self.timeout)

        self.time_tip_label = QLabel()
        MainWindow.statusBar().addPermanentWidget(self.time_tip_label, stretch=0)

        url = "<a href='https://meanwey.com' target='_blank'>小明同学</a>"
        self.url_label = QLabel()
        self.url_label.setText(url)
        self.url_label.setOpenExternalLinks(True)
        MainWindow.statusBar().addPermanentWidget(self.url_label, stretch=0)

    def timeout(self):
        """显示时间"""
        time = QDateTime.currentDateTime()
        time_str = time.toString("yyyy-MM-dd hh:mm:ss")
        self.time_tip_label.setText(time_str)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "批量修改文件名-小明同学"))

        MainWindow.setStatusTip(_translate("MainWindow", "欢迎使用本程序~"))

        self.new_label.setText(_translate("MainWindow", "新文件名"))
        self.old_label.setText(_translate("MainWindow", "原文件名"))

        self.confirm_btn.setText(_translate("MainWindow", "确认并生成新文件名"))
        self.first_name_label.setText(_translate("MainWindow", "输入起始文件名:"))

        self.menu.setTitle(_translate("MainWindow", "文件"))
        self.menu_2.setTitle(_translate("MainWindow", "帮助"))

        self.actiondakai.setText(_translate("MainWindow", "打开文件"))
        self.actiondakai.setStatusTip(_translate("MainWindow", "打开您想要修改文件"))
        self.actiondakai.setShortcut(_translate("MainWindow", "Ctrl+O"))

        self.actionxiugai.setText(_translate("MainWindow", "确认修改"))
        self.actionxiugai.setStatusTip(_translate("MainWindow", "确认无误后进行重命名!"))

        self.actionclear.setText(_translate("MainWindow", "清除"))

        self.actiontuichu.setText(_translate("MainWindow", "退出"))
        self.actiontuichu.setStatusTip(_translate("MainWindow", "退出程序"))
        self.actiontuichu.setShortcut(_translate("MainWindow", "Ctrl+Q"))

        self.actionshiyong.setText(_translate("MainWindow", "使用帮助"))
        self.actionshiyong.setStatusTip(_translate("MainWindow", "程序使用帮助"))
        self.actionguanyu.setText(_translate("MainWindow", "关于"))
        self.actionguanyu.setStatusTip(_translate("MainWindow", "关于本程序"))
        self.actionlianxizuozhe.setText(_translate("MainWindow", "联系作者"))
        self.actionlianxizuozhe.setStatusTip(_translate("MainWindow", "联系作者"))
  • 4 打开文件函数

class Ui_MainWindow(object):
    ...
    def openfile_window(self):
        """打开文件窗口"""
        files, types = QFileDialog.getOpenFileNames(None,
                                                    "选择文件",
                                                    "./",
                                                    "All Files (*)")
        if files:
            file_path = files[0].rsplit('/', maxsplit=1)[0]
            MainWindow.setStatusTip(QtCore.QCoreApplication.translate("MainWindow",
                                                                      "当前操作路径:%s/[共%s个文件]" % (file_path, len(files))))

            for file in files:
                self.old_list.addItem(file)
            return files
        else:
            self.info('您没有选择文件!')

    def openfile(self):
        """打开文件"""
        if not self.old_list:
            self.openfile_window()
        else:
            reply = self.question('当前已经打开了文件,是否取消当前重新打开?')
            if reply == QMessageBox.Yes:
                self.old_list.clear()
                self.openfile_window()
  • 5 获取原文件名并显示

class Ui_MainWindow(object):
    ...
    def get_old_file_name_list(self):
        """获取原文件名"""
        old_file_name_list = []
        file_count = self.old_list.count()

        for i in range(file_count):
            old_file_name_list.append(self.old_list.item(i).text())
        return old_file_name_list, file_count
  • 6 生成新文件名

class Ui_MainWindow(object):
    ...
    def create_new_name(self):
        """生成新文件名功能函数"""
        old_file_name_list, file_count = self.get_old_file_name_list()
        file_path = os.path.dirname(self.old_list.item(0).text())

        for i in range(file_count):
            old_file_name_list.append(self.old_list.item(i).text())

        try:
            first_name = self.first_name_input.text()
            start_num = re.findall('\d+$', first_name)  # 正则表达式获取用户输入的文件名

            new_file_name_list = []
            if start_num:
                start_num = int(start_num[0])
                first_name_str = first_name.rsplit(str(start_num), 1)[0]
            else:
                start_num = 0
                first_name_str = first_name
            for i in range(file_count):
                new_file_name = file_path + '/' + first_name_str + str(start_num) + '.' + \
                                old_file_name_list[i].split('.')[-1]
                start_num += 1
                self.new_list.addItem(new_file_name)
                new_file_name_list.append(new_file_name)
        except Exception as e:
            print(e)

    def create_new_file_name_list(self):
        """生成新文件名"""
        if len(self.first_name_input.text()) and self.old_list:
            if self.new_list:
                reply = self.question("您已经生成了新文件,是否进行修改并重新生成?")
                if reply == QMessageBox.Yes:
                    self.new_list.clear()
                    self.create_new_name()
            else:
                self.create_new_name()
        else:
            self.info("请先打开文件并输入起始文件名!")

    def get_new_file_name_list(self):
        """获取新文件名"""
        new_file_name_list = []
        file_count = self.new_list.count()

        for i in range(file_count):
            new_file_name_list.append(self.new_list.item(i).text())
        return new_file_name_list
  • 7 重命名操作

class Ui_MainWindow(object):
    ...
    def re_name(self):
        """重命名"""
        old_file_name_list, file_count = self.get_old_file_name_list()
        if not old_file_name_list:
            self.info("请先打开文件!")
        else:
            if not len(self.first_name_input.text()):
                self.info("请先输入起始文件名!")
            else:
                new_file_name_list = self.get_new_file_name_list()
                if not new_file_name_list:
                    self.info("请先生成新文件名!")
                else:
                    reply = self.question("确认无误,按下[Yes]进行重命名!(不可撤销,操作前做好备份!)")
                    if reply == QMessageBox.Yes:
                        start = time.time()
                        for i in range(file_count):
                            os.rename(old_file_name_list[i], new_file_name_list[i])
                        end = time.time()
                        user_time = end - start
                        self.info("操作成功,本次更改[%s]个文件,共用时%.3fs~" % (file_count, user_time))
  • 8 清除数据

class Ui_MainWindow(object):
    ...
    def clear_data(self):
        """清除"""
        if self.old_list or self.new_list or len(self.first_name_input.text()):
            reply = self.info('是否清除数据?(不会删除文件~)')
            if reply == QMessageBox.Ok:
                self.old_list.clear()
                self.new_list.clear()
                self.first_name_input.clear()
        else:
            self.info("暂无内容清理~")
  • 9 相关提示框

class Ui_MainWindow(object):
    ...
    def question(self, msg):
        """询问窗口对话框"""
        reply = QMessageBox.question(None, '提示', msg,
                                     QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel,
                                     QMessageBox.No)
        return reply

    def info(self, msg):
        """信息提示窗口"""
        reply = QMessageBox.information(None, '提示', msg, QMessageBox.Ok | QMessageBox.Close,
                                        QMessageBox.Close)
        return reply

    def about(self):
        msg = """批量修改文件名-小明同学 V1.0\n欢迎大家使用该小程序,用作批量修改文件名(默认覆盖原文件,所以使用前做好备份!),\
该程序目前还在优化阶段可能还有诸多bug,欢迎提出意见!"""
        msgBox = QMessageBox(QMessageBox.NoIcon, '关于', msg)
        msgBox.exec()

    def help(self):
        msg = """① 点击[文件]→[打开文件],打开您想修改的文件;\n② 在输入框中输入起始文件名;\n\
③ 输入起始文件名后点击[确认并生成新文件名],程序会生成对应的新文件名;\n\
④ 确认无误后,点击[文件]→[确认修改],则程序会自动修改文件名;\n\
⑤ 点击[文件]→[清除],清除本次操作内容(不会删除文件),方便执行下次操作!
        """
        msgBox = QMessageBox(QMessageBox.NoIcon, '使用帮助', msg)
        msgBox.exec()

    def contact_me(self):
        msg = """        【小明同学】\n\
Email:meanwey@qq.com\n\
网 址:https://meanwey.com
"""
        msgBox = QMessageBox(QMessageBox.NoIcon, '联系作者', msg)
        msgBox.exec()
  • 10 执行程序

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

最后附效果图:

上一篇 - 忆高考

下一篇 - 红楼到头一场梦

提交评论

未登录,登录后方便交流评论~ 登录 or 注册

评论列表

暂无评论