当前位置: 代码网 > it编程>前端脚本>Python > Python实现批量获取文件夹内文件名并重命名

Python实现批量获取文件夹内文件名并重命名

2025年02月10日 Python 我要评论
1、背景介绍有时候我们经常需要将批量的文件进行重命名,比如:① 批量在文件名【前面】加上 自定义字符② 批量在文件名【后面】加上 自定义字符③ 批量在【替换】文件名中的字符④ 批量去除 空格⑤ 结果可

1、背景介绍

有时候我们经常需要将批量的文件进行重命名,比如:

  • ① 批量在文件名【前面】加上 自定义字符
  • ② 批量在文件名【后面】加上 自定义字符
  • ③ 批量在【替换】文件名中的字符
  • ④ 批量去除 空格
  • ⑤ 结果可以选择复制文件 或者 移动 文件

2、库的安装

用途安装
pyqt5界面设计pip install pyqt5 -i https://pypi.tuna.tsinghua.edu.cn/simple/
shutil文件移动内置库无需安装
os文件移动内置库无需安装

3、核心代码

复制 或 移动

shutil.move(old_file, new_file)  # 移动文件
shutil.copy2(old_file, new_file)  # 复制文件

4、完整代码

# -*- coding: utf-8 -*-
'''
@project :测试 
@file    :文件重命名.py
@ide     :pycharm 
@author  :一晌小贪欢(278865463@qq.com)
@date    :2025/2/7 下午8:02 
'''


import os
import shutil
from pyqt5.qtwidgets import qapplication, qwidget, qlabel, qlineedit, qvboxlayout, qhboxlayout, qpushbutton, qfiledialog, qcheckbox, qformlayout, qspinbox, qgroupbox, qdialogbuttonbox, qradiobutton, qbuttongroup


def copy_or_move_files(folder_path, new_folder_path, prefix="", suffix="", replace_chars=none, add_index=false, remove_spaces=false, move_files=false):
    # 检查源文件夹是否存在
    if not os.path.exists(folder_path):
        raise filenotfounderror(f"folder '{folder_path}' does not exist.")

    # 检查目标文件夹是否存在,不存在则创建
    if not os.path.exists(new_folder_path):
        os.makedirs(new_folder_path)
    index = 0
    # 遍历文件夹内所有文件
    for filename in os.listdir(folder_path):
        # 构造完整文件路径
        old_file = os.path.join(folder_path, filename)

        # 判断是否为文件(排除文件夹)
        if os.path.isfile(old_file):
            # 分割文件名和扩展名
            name_only, extension = os.path.splitext(filename)

            # 生成新文件名
            new_name = name_only
            if prefix:
                new_name = prefix + new_name
            if suffix:
                new_name = new_name + suffix
            if replace_chars:
                old_char, new_char = replace_chars
                new_name = new_name.replace(old_char, new_char)

            if remove_spaces:
                new_name = new_name.replace(" ", "")  # 去除空格

            if add_index:
                index += 1
                name_only, extension = os.path.splitext(filename)  # 分离原始文件名和扩展名
                new_name_base = prefix + name_only + suffix  # 生成基础的新文件名
                new_name = f"{index}{new_name_base}{extension}"  # 在文件名最前面添加索引
            # 重新组合文件名和扩展名
            new_name = new_name + extension

            new_file = os.path.join(new_folder_path, new_name)

            # 根据用户选择执行复制或移动操作
            if move_files:
                shutil.move(old_file, new_file)  # 移动文件
                print(f"moved '{filename}' to '{new_name}'")
            else:
                shutil.copy2(old_file, new_file)  # 复制文件
                print(f"copied '{filename}' to '{new_name}'")


class filecopyapp(qwidget):
    def __init__(self):
        super().__init__()

        self.setwindowtitle("文件重命名—复制版")
        self.setgeometry(900, 500, 600, 300)

        # initialize ui components
        self.init_ui()

    def init_ui(self):
        # create layout
        layout = qvboxlayout()

        # source folder
        self.folder_label = qlabel("源文件:")
        self.folder_line_edit = qlineedit()
        self.browse_button = qpushbutton("浏览")
        self.browse_button.clicked.connect(self.browse_folder)

        # destination folder
        self.new_folder_label = qlabel("保存文件夹:")
        self.new_folder_line_edit = qlineedit()
        self.new_folder_button = qpushbutton("浏览")
        self.new_folder_button.clicked.connect(self.browse_new_folder)

        # prefix, suffix, char replacement
        self.prefix_label = qlabel("头部添加:")
        self.prefix_line_edit = qlineedit()

        self.suffix_label = qlabel("尾部添加:")
        self.suffix_line_edit = qlineedit()

        self.old_char_label = qlabel("原字符:")
        self.old_char_line_edit = qlineedit()
        self.new_char_label = qlabel("替换字符:")
        self.new_char_line_edit = qlineedit()

        # index and space removal
        self.add_index_check_box = qcheckbox("重复名称添加索引")
        self.remove_spaces_check_box = qcheckbox("去除文件名中的空格")

        # copy or move radio buttons
        self.copy_radio = qradiobutton("复制")
        self.move_radio = qradiobutton("移动")
        self.copy_radio.setchecked(true)  # 默认选择复制
        self.action_group = qbuttongroup()
        self.action_group.addbutton(self.copy_radio)
        self.action_group.addbutton(self.move_radio)

        # start button
        self.start_button = qpushbutton("开始")
        self.start_button.clicked.connect(self.start_copy_or_move)

        # arrange components
        folder_layout = qhboxlayout()
        folder_layout.addwidget(self.folder_label)
        folder_layout.addwidget(self.folder_line_edit)
        folder_layout.addwidget(self.browse_button)

        new_folder_layout = qhboxlayout()
        new_folder_layout.addwidget(self.new_folder_label)
        new_folder_layout.addwidget(self.new_folder_line_edit)
        new_folder_layout.addwidget(self.new_folder_button)

        replace_layout = qformlayout()
        replace_layout.addrow(self.prefix_label, self.prefix_line_edit)
        replace_layout.addrow(self.suffix_label, self.suffix_line_edit)
        replace_layout.addrow(self.old_char_label, self.old_char_line_edit)
        replace_layout.addrow(self.new_char_label, self.new_char_line_edit)

        options_layout = qvboxlayout()
        options_layout.addwidget(self.add_index_check_box)
        options_layout.addwidget(self.remove_spaces_check_box)

        # copy or move layout
        action_layout = qhboxlayout()
        action_layout.addwidget(self.copy_radio)
        action_layout.addwidget(self.move_radio)

        # layout adjustments
        layout.addlayout(folder_layout)
        layout.addlayout(new_folder_layout)
        layout.addlayout(replace_layout)
        layout.addlayout(options_layout)
        layout.addlayout(action_layout)
        layout.addwidget(self.start_button)

        # set main layout
        self.setlayout(layout)

    def browse_folder(self):
        folder_path = qfiledialog.getexistingdirectory(self, "选择源文件夹")
        if folder_path:
            self.folder_line_edit.settext(folder_path)

    def browse_new_folder(self):
        new_folder_path = qfiledialog.getexistingdirectory(self, "选择保存文件夹")
        if new_folder_path:
            self.new_folder_line_edit.settext(new_folder_path)

    def start_copy_or_move(self):
        folder_path = self.folder_line_edit.text()
        new_folder_path = self.new_folder_line_edit.text()
        prefix = self.prefix_line_edit.text()
        suffix = self.suffix_line_edit.text()
        replace_chars = (
            self.old_char_line_edit.text(), self.new_char_line_edit.text()) if self.old_char_line_edit.text() and self.new_char_line_edit.text() else none
        add_index = self.add_index_check_box.ischecked()
        remove_spaces = self.remove_spaces_check_box.ischecked()
        move_files = self.move_radio.ischecked()  # 判断用户选择的是复制还是移动
        copy_or_move_files(folder_path, new_folder_path, prefix, suffix, replace_chars, add_index, remove_spaces, move_files)


if __name__ == '__main__':
    import sys
    app = qapplication(sys.argv)
    window = filecopyapp()
    window.show()
    sys.exit(app.exec_())

5、效果图

到此这篇关于python实现批量获取文件夹内文件名并重命名的文章就介绍到这了,更多相关python文件重命名内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com