Python批量实现给文件夹添加文件

 更新时间:2025年09月24日 09:59:45   作者:阿幸软件杂货间  
这篇文章主要为大家详细介绍了如何使用Python批量实现给文件夹添加文件功能,文中的示例代码讲解详细,有需要的小伙伴可以跟随小编一起学习一下

代码功能介绍

这个代码的功能就是一个,给某个文件夹里面添加某个文件(含父级文件夹下的每一个子文件夹)

举个例子,父级文件夹是:“D:\Desktop\1,要添加的文件路径是:D:\1.txt”

则最后会把文件1.txt复制到文件夹D:\Desktop\1里面去。

代码界面截图

完整代码

下面是现成的源码

import sys
import os
import shutil
import webbrowser
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton, QLabel, 
                            QLineEdit, QVBoxLayout, QHBoxLayout, QWidget, 
                            QTextEdit, QMessageBox, QFileDialog)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont, QPalette, QColor

class FileCopyTool(QMainWindow):
    def __init__(self):
        super().__init__()
        # 定义颜色常量
        self.BUTTON_BLUE = QColor(33, 150, 243)     # 按钮蓝色(#2196F3)
        self.BUTTON_GREEN = QColor(76, 175, 80)     # 按钮绿色(#4CAF50)
        self.BUTTON_RED = QColor(244, 67, 54)       # 按钮红色(#f44336)
        self.LINE_EDIT_BG = QColor(245, 245, 245)   # 文本框背景色(浅灰色)
        self.folder_list = []  # 存储多个文件夹路径
        self.initUI()
        
    def initUI(self):
        # 设置窗口标题和大小
        self.setWindowTitle('文件批量复制工具@阿幸')
        self.setGeometry(100, 100, 900, 600)
        self.setMinimumSize(800, 500)
        
        # 创建中心部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(15, 15, 15, 15)
        main_layout.setSpacing(12)
        
        # 批量文件夹区域
        batch_folder_layout = QHBoxLayout()
        batch_folder_layout.setSpacing(10)
        
        self.batch_folder_label = QLabel('文件夹路径:')
        self.batch_folder_label.setFont(QFont("Microsoft YaHei", 10))
        self.batch_folder_label.setFixedWidth(100)
        self.batch_folder_label.setAlignment(Qt.AlignVCenter | Qt.AlignRight)
        
        self.batch_folder_edit = QLineEdit()
        self.setup_line_edit_bg(self.batch_folder_edit)
        self.batch_folder_edit.setFont(QFont("Microsoft YaHei", 10))
        # 设置默认文件夹路径
        self.default_folder = r"D:\Desktop\文件存储"
        # 检查默认路径是否存在
        if os.path.exists(self.default_folder):
            self.folder_list = [self.default_folder]
            self.batch_folder_edit.setText(self.default_folder)
        else:
            self.batch_folder_edit.setPlaceholderText("已选择 0 个文件夹")
        self.batch_folder_edit.setReadOnly(True)
        
        self.batch_folder_btn = self.create_browse_button("浏览", self.select_batch_folders, self.BUTTON_GREEN)
        
        self.clear_batch_btn = self.create_browse_button("清空", self.clear_batch_folders, self.BUTTON_RED)
        
        batch_folder_layout.addWidget(self.batch_folder_label)
        batch_folder_layout.addWidget(self.batch_folder_edit, 1)
        batch_folder_layout.addWidget(self.batch_folder_btn)
        batch_folder_layout.addWidget(self.clear_batch_btn)
        
        # 源文件路径区域
        source_file_layout = QHBoxLayout()
        source_file_layout.setSpacing(10)
        
        self.source_file_label = QLabel('文件路径:')
        self.source_file_label.setFont(QFont("Microsoft YaHei", 10))
        self.source_file_label.setFixedWidth(100)
        self.source_file_label.setAlignment(Qt.AlignVCenter | Qt.AlignRight)
        
        self.source_file_edit = QLineEdit()
        self.setup_line_edit_bg(self.source_file_edit)
        self.source_file_edit.setFont(QFont("Microsoft YaHei", 10))
        self.source_file_edit.setText(r"D:\1.txt")
        
        self.source_file_btn = self.create_browse_button("浏览", self.select_source_file, self.BUTTON_BLUE)
        
        source_file_layout.addWidget(self.source_file_label)
        source_file_layout.addWidget(self.source_file_edit, 1)
        source_file_layout.addWidget(self.source_file_btn)
        
        # 功能按钮区域
        button_layout = QHBoxLayout()
        button_layout.setSpacing(20)
        button_layout.setContentsMargins(0, 5, 0, 5)
        
        self.copy_button = QPushButton('开始批量复制')
        self.copy_button.setFont(QFont("Microsoft YaHei", 12, QFont.Bold))
        self.copy_button.setFixedSize(150, 40)
        self.copy_button.clicked.connect(self.start_copy)
        self.setup_button_style(self.copy_button, self.BUTTON_BLUE)
        
        self.advanced_button = QPushButton('高级功能')
        self.advanced_button.setFont(QFont("Microsoft YaHei", 12, QFont.Bold))
        self.advanced_button.setFixedSize(120, 40)
        self.advanced_button.clicked.connect(self.open_advanced)
        self.setup_button_style(self.advanced_button, self.BUTTON_GREEN)
        
        button_layout.addStretch(1)
        button_layout.addWidget(self.copy_button, alignment=Qt.AlignCenter)
        button_layout.addWidget(self.advanced_button, alignment=Qt.AlignCenter)
        button_layout.addStretch(1)
        
        # 日志显示区域
        log_container = QVBoxLayout()
        log_container.setSpacing(5)
        
        self.log_label = QLabel('操作日志:')
        self.log_label.setFont(QFont("Microsoft YaHei", 10, QFont.Bold))
        
        self.log_text = QTextEdit()
        self.log_text.setReadOnly(True)
        self.log_text.setFont(QFont("Microsoft YaHei", 10))
        self.setup_line_edit_bg(self.log_text)
        
        log_container.addWidget(self.log_label)
        log_container.addWidget(self.log_text)
        
        # 添加所有组件到主布局
        main_layout.addLayout(batch_folder_layout)
        main_layout.addLayout(source_file_layout)
        main_layout.addLayout(button_layout)
        main_layout.addLayout(log_container, 1)
        
    def create_browse_button(self, text, callback, color):
        """创建统一风格的按钮"""
        button = QPushButton(text)
        button.setFont(QFont("Microsoft YaHei", 10, QFont.Bold))
        button.setFixedWidth(80)
        button.clicked.connect(callback)
        self.setup_button_style(button, color)
        return button
        
    def setup_line_edit_bg(self, widget):
        """设置文本框背景颜色"""
        palette = widget.palette()
        palette.setColor(QPalette.Base, self.LINE_EDIT_BG)
        palette.setColor(QPalette.Text, QColor(0, 0, 0))
        widget.setPalette(palette)
        widget.setAutoFillBackground(True)
        
    def setup_button_style(self, button, base_color):
        """设置按钮样式"""
        button.setStyleSheet(f"""
            QPushButton {{
                background-color: rgb({base_color.red()}, {base_color.green()}, {base_color.blue()});
                color: white;
                border: none;
                padding: 5px;
                border-radius: 4px;
            }}
            QPushButton:hover {{
                background-color: rgb({int(base_color.red()*0.8)}, {int(base_color.green()*0.8)}, {int(base_color.blue()*0.8)});
            }}
            QPushButton:pressed {{
                background-color: rgb({int(base_color.red()*0.7)}, {int(base_color.green()*0.7)}, {int(base_color.blue()*0.7)});
            }}
        """)
        button.setFocusPolicy(Qt.NoFocus)

    # 文件夹选择功能
    def select_batch_folders(self):
        """选择多个文件夹并显示路径"""
        folder = QFileDialog.getExistingDirectory(self, "选择文件夹", self.default_folder)
        if folder:
            if folder not in self.folder_list:
                self.folder_list.append(folder)
                # 显示所有已选择的文件夹路径,用分号分隔
                self.batch_folder_edit.setText("; ".join(self.folder_list))
                QMessageBox.information(self, '成功', f'已添加 {len(self.folder_list)} 个文件夹')
    
    def clear_batch_folders(self):
        """清空已选择的批量文件夹"""
        self.folder_list.clear()
        self.batch_folder_edit.clear()
        self.batch_folder_edit.setPlaceholderText("已选择 0 个文件夹")
        QMessageBox.information(self, '提示', '已清空所有选择的文件夹')

    # 文件选择功能
    def select_source_file(self):
        file, _ = QFileDialog.getOpenFileName(self, "选择源文件", os.path.dirname(self.source_file_edit.text()))
        if file:
            self.source_file_edit.setText(file)
        
    def start_copy(self):
        """批量复制逻辑"""
        source_file = self.source_file_edit.text().strip()
        
        # 验证源文件
        if not source_file or not os.path.isfile(source_file):
            QMessageBox.warning(self, '文件错误', '请输入有效的源文件路径')
            return
            
        # 验证批量文件夹
        if not self.folder_list:
            QMessageBox.warning(self, '路径错误', '请选择至少一个文件夹')
            return
            
        self.log_text.clear()
        try:
            # 遍历所有目标文件夹
            for folder in self.folder_list:
                # 复制文件到每个目标文件夹的子文件夹中
                for root, dirs, files in os.walk(folder):
                    for dir in dirs:
                        dest_path = os.path.join(root, dir, os.path.basename(source_file))
                        try:
                            shutil.copy2(source_file, dest_path)
                            self.log_text.append(f"已复制到:{dest_path}")
                        except Exception as e:
                            self.log_text.append(f"复制失败到 {dest_path}: {e}")
            
            QMessageBox.information(self, '完成', '批量复制操作已完成')
        except Exception as e:
            QMessageBox.critical(self, '错误', f'操作过程中发生错误: {str(e)}')
    
    def open_advanced(self):
        webbrowser.open("你自己的")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyle("Fusion")
    window = FileCopyTool()
    window.show()
    sys.exit(app.exec_())
    

源码打包

1、你需要安装Python(不会安装的自行解决)

2、下载我提供的源码文件

3、将源码文件放在Python路径下

4、打开cmd界面,输入:“D:\Program Files (x86)\biancheng\python3113\python.exe” -m PyInstaller --onefile --windowed “D:\Program Files (x86)\biancheng\python3113\批量给文件夹添加文件v2.py”

其中D:\Program Files (x86)\biancheng\python3113要替换为你自己的Python路径

到此这篇关于Python批量实现给文件夹添加文件的文章就介绍到这了,更多相关Python文件复制内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python print无法打印\r的问题及解决

    python print无法打印\r的问题及解决

    这篇文章主要介绍了python print无法打印\r的问题及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-08-08
  • django中的*args 与 **kwargs使用介绍

    django中的*args 与 **kwargs使用介绍

    这篇文章主要介绍了django中的*args 与 **kwargs使用介绍,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-03-03
  • Python YAML文件的读写操作详解

    Python YAML文件的读写操作详解

    这篇文章主要介绍了Python读写yaml文件,yaml 是专门用来写配置文件的语言,非常简洁和强大,之前用ini也能写配置文件,有点类似于json格式,下面关于Python读写yaml文件的详细资料,需要的小伙伴可以参考一下
    2022-08-08
  • Python列表插入元素到指定位置的5种高效技巧

    Python列表插入元素到指定位置的5种高效技巧

    本文主要介绍了Python列表插入元素到指定位置的5种高效方法,解决动态数据处理难题,涵盖insert()、切片、extend()等多种技巧,适用于列表实时更新场景,感兴趣的可以了解一下
    2026-04-04
  • 使用python批量生成insert语句的方法

    使用python批量生成insert语句的方法

    很多时候需要造数据,大量的插入数据,本文介绍了使用python批量生成insert语句的方法,需要的朋友们下面随着小编来一起学习学习吧
    2021-05-05
  • 利用Python操作Word文档页码的实际应用

    利用Python操作Word文档页码的实际应用

    在撰写长篇文档时,经常需要将文档分成多个节,每个节都需要单独的页码,下面这篇文章主要介绍了利用Python操作Word文档页码的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2025-09-09
  • Python调用腾讯云短信服务发送手机短信

    Python调用腾讯云短信服务发送手机短信

    这篇文章主要为大家介绍了Python调用腾讯云短信服务发送手机短信,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-05-05
  • 最强Python可视化绘图库Plotly详解用法

    最强Python可视化绘图库Plotly详解用法

    数据分析离不开数据可视化。Plotly 是一款用来做数据分析和可视化的在线平台,功能非常强大,可以在线绘制很多图形比如条形图、散点图、饼图、直方图等等
    2021-11-11
  • Python Logging库完全指南

    Python Logging库完全指南

    本文主要介绍了Python Logging库完全指南,包括为什么使用Logging、快速开始、核心配置、进阶技巧和实用场景示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2026-02-02
  • python基于plotly实现画饼状图代码实例

    python基于plotly实现画饼状图代码实例

    这篇文章主要介绍了python基于plotly实现画饼状图代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12

最新评论