[多进程]使用python实现多进程高并发copy文件夹中多个大文件夹内容到指定目标

#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
需求:文件夹多个大文件内容高并发copy器
需求分析:
    1. 目标文件夹是否存在,如果不存在就创建,如果存在则不创建
    2. 遍历文件夹中的所有文件,并拷贝到目标文件夹
    3. 采用进程实现多任务,完成高并发拷贝
"""
import os
import multiprocessing


def copy_file(file_name, source_dir, dest_dir):
    pass
    # 1. 拼接源文件路径和目标文件路径
    source_path = source_dir + "/" + file_name
    dest_path = dest_dir + "/" + file_name
    # 2. 打开源文件和目标文件
    with open(source_path, "rb") as source_file:
        with open(dest_path, "wb") as dest_file:
            # 3. 循环读取源文件到目标路径
            while True:
                data = source_file.read(1024)  # 每次读取1024个字节
                if data:
                    dest_file.write(data)
                else:
                    break
    print (file_name + "文件拷贝完成")


if __name__ == '__main__':
    # 1. 定义源文件夹和目标文件夹
    source_dir = "python学习视频"
    dest_dir = "./目标文件夹"

    # 2. 创建目标文件夹
    try:
        os.mkdir(dest_dir)
    except:
        print ("目标文件夹已经存在")

    # 3.读取源文件夹的文件列表
    file_list = os.listdir(source_dir)

    # 4.遍历文件列表实现拷贝
    for file_name in file_list:
        # copy_file(file_name, source_dir, dest_dir)
        # 5. 使用多进程实现多任务拷贝
        sub_process = multiprocessing.Process(target=copy_file,
                                              args=(file_name, source_dir, dest_dir))
        # 子进程sub_process.daemon的值默认为False,表示非守护进程,即使主进程结束,子进程仍然运行直到自己结束
        # 如果将sub_process设置为True,则表示sub_process守护主进程,
        # 主进程结束时,若子进程未运行结束,则子进程会自动销毁,不再执行子进程代码
        # 如果将sub_process设置为True,可能导致source_dir中的文件不能被全部拷贝
        sub_process.start()
    print ("主线程结束")

猜你喜欢

转载自blog.csdn.net/weixin_45329445/article/details/113446342