Python多线程拷贝指定文件到目标目录

需要源代码可私信

方案一: 直接套用脚本,需可以看懂一些脚本逻辑

这个函数使用 threading 模块来创建多个线程,并将每个线程分配到不同的目标目录中进行 txt 文件拷贝。每个线程都会执行 copy_txt_files 函数来拷贝指定目录中的 txt 文件。

import os
import shutil
import threading
import time

def copy_all_txt_files(source_dir, target_dirs, num_threads=10):
    """
    从源目录拷贝所有 txt 文件到多个不同的目标目录

    参数:
    source_dir:源目录路径
    target_dirs:目标目录路径组成的列表
    num_threads:线程数量,默认为 10

    """

    def copy_txt_files(source_dir, target_dir):
        """
        拷贝 txt 文件的函数,被多线程调用

        参数:
        source_dir:源目录路径
        target_dir:目标目录路径

        """
        txt_files = [f for f in os.listdir(source_dir) if os.path.isfile(os.path.join(source_dir, f)) and f.endswith(".txt")]
        for txt_file in txt_files:
            shutil.copy(os.path.join(source_dir, txt_file), os.path.join(target_dir, txt_file))

    # 创建多个线程并启动
    threads = []
    start_time = time.time()
    for target_dir in target_dirs:
        t = threading.Thread(target=copy_txt_files, args=(source_dir, target_dir))
        t.daemon = True
        t.start()
        threads.append(t)

    # 等待所有线程结束
    for t in threads:
        t.join()

    end_time = time.time()

    print(f"拷贝文件总共花费了 {(end_time-start_time):.2f} 秒")
    # 示例用法
copy_all_txt_files("/path/folder", ["/path/folder1", "/path/folder2"], num_threads=6)

方案二:直接调用封装脚本(写用例,执行脚本即可)

脚本实现封装后,只需要在ThreadProcessCopy.yaml文件中写用例即可,此后执行Threadprocess_Copy.py脚本即实现多线程拷贝文件夹下所有指定的文件如(.txt、.exe等结尾的文件)到指定目录

目录介绍:
在这里插入图片描述

ThreadProcessCopy.yaml用例编写配置拷贝文件的源地址和目标地址

source_folder: 原始文件夹路径

dest_folders: 需存放目标文件夹,可多个同时填写

endswith: 特殊文件以什么结尾的 如 .txt .exe .dll 等等

num_threads:线程数 可自定义

ThreadingProcess:
  source_folder: \\127.0.0.1\d$\exportdir
  dest_folders:
    - \\127.0.0.2\d$\p
    - \\127.0.0.3\d$\p
  endswith: .txt
  num_threads: 5

PublicConfig.py脚本: 配置读取信息,方便调用

import os
from Public_Utils.util_yaml import YamlReader

class YamlPath:
    def __init__(self):
        current = os.path.abspath(__file__)
        self.base_dir = os.path.dirname(os.path.dirname(current))
        self._config_path = self.base_dir + os.sep + "Public_Config\Public_yaml"

    def get_threadprocess_file(self):
        self._config_file = self._config_path + os.sep + "ThreadProcessCopy.yaml"
        return self._config_file

class ConfigYaml:
    def __init__(self):   #初始yaml读取配置文件
        self.threadprocess_config = YamlReader(YamlPath().get_threadprocess_file()).yaml_data()

    def get_threadprocess_yaml(self):
        return self.threadprocess_config['ThreadingProcess']

if __name__ == '__main__':
    pass

Threadprocess_Copy.py执行脚本

import os
import shutil
import threading
import time

from Public_Config.PublicConfig import ConfigYaml

class ThreadProcess:

    def copy_all_sepcial_files(self,num_threads):
        """
        拷贝 txt 文件的函数,被多线程调用
        参数:
        source_dir:源目录路径
        target_dir:目标目录路径

        """
        source_dir = ConfigYaml().get_threadprocess_yaml()['source_folder']  # 需要复制的原始文件夹
        target_dirs = ConfigYaml().get_threadprocess_yaml()['dest_folders']  # 需要复制到的目标文件夹
        def copy_special_files(source_dir, target_dir):
            txt_files = [f for f in os.listdir(source_dir) if os.path.isfile(os.path.join(source_dir, f)) and f.endswith(ConfigYaml().get_threadprocess_yaml()['endswith'])]
            for txt_file in txt_files:
                shutil.copy(os.path.join(source_dir, txt_file), os.path.join(target_dir, txt_file))

        #创建多个线程并启动
        threads = []
        start_time = time.time()
        for target_dir in target_dirs:
            t = threading.Thread(target=copy_special_files,args=(source_dir,target_dir))
            t.daemon = True
            t.start()
            threads.append(t)

        #等待所有线程结束
        for t in threads:
            t.join()
        end_time = time.time()
        elapsed_time = end_time - start_time
        print(f"拷贝总共花费{elapsed_time:.2f}秒")

if __name__ == '__main__':
    ThreadProcess().copy_all_sepcial_files(num_threads = ConfigYaml().get_threadprocess_yaml()['num_threads'])
    pass

util_yaml.py

import os
import yaml

class YamlReader:
    #初始化,判断文件是否存在
    def __init__(self,yaml_file):
        if os.path.exists(yaml_file):
            self.yaml_file = yaml_file
        else:
            raise FileNotFoundError("yaml文件不存在")
        self._data = None
        self._data_all = None

    def yaml_data(self):  #yaml文件读取 --单个文档读取
        #第一次调用data,读取yaml文档,如果不是,直接返回之前保存的数据
        if not self._data:
            with open(self.yaml_file,'rb') as f:
                self._data = yaml.safe_load(f)
        return self._data

    def yaml_data_all(self):  #多个文档的读取
        if not self._data_all:
            with open(self.yaml_file,'rb') as f:
                self._data_all = yaml.safe_load_all(f)
        return self._data_all
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个使用Python多线程拷贝文件的示例代码: ```python import os import shutil import threading def copy_file(source_file, dest_dir): # 使用shutil.copy()复制文件 shutil.copy(source_file, dest_dir) def copy_big_file(source_file, dest_dir, chunk_size=1024*1024*10, thread_num=4): # 获取源文件大小 file_size = os.path.getsize(source_file) # 计算每个线程的拷贝大小 chunk_size = min(chunk_size, file_size // thread_num) # 创建目标目录 os.makedirs(dest_dir, exist_ok=True) # 启动多个线程执行文件拷贝任务 threads = [] for i in range(thread_num): start = i * chunk_size end = start + chunk_size if i == thread_num - 1: end = file_size t = threading.Thread(target=copy_file, args=(source_file, dest_dir)) t.start() threads.append(t) # 等待所有线程完成任务 for t in threads: t.join() # 示例用法 source_file = "/path/to/bigfile" dest_dir = "/path/to/destination" copy_big_file(source_file, dest_dir, chunk_size=1024*1024*100, thread_num=4) ``` 在上述示例代码中,我们定义了一个`copy_big_file()`函数来实现文件拷贝。该函数接受三个参数:源文件路径`source_file`、目标目录路径`dest_dir`和可选的两个参数`chunk_size`和`thread_num`。`chunk_size`表示每个线程拷贝的大小,如果该值过大,可能会导致内存消耗过大;`thread_num`表示启动的线程数。 在函数实现中,我们首先获取文件大小,然后计算出每个线程拷贝的大小`chunk_size`,并创建目标目录。接着,我们启动多个线程执行文件拷贝任务,每个线程拷贝文件块大小为`chunk_size`。最后,我们等待所有线程完成任务。 需要注意的是,在上述示例代码中,我们使用了`shutil.copy()`函数来实现文件拷贝。在拷贝文件时,如果将整个文件全部读入内存中再写入目标文件,可能会导致内存消耗过大,甚至导致程序崩溃。因此,我们建议使用`shutil.copy()`来进行文件拷贝,该函数会自动处理文件块,避免了内存消耗过大的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

经历一个春

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值