多进程实现文件拷贝

多进程实现文件拷贝

import multiprocessing
import os
import shutil
"""
    拷贝文件任务:
    filename: 文件名
    src_dir:源目录
    dst_dir:目标目录

"""
def copy_file(file_name, src_dir, dst_dir):
    # 源文件的路径
    src_file_path = src_dir + "/" + file_name
    # 目标文件的路径
    dst_file_path = dst_dir + "/" + file_name

    # 创建或者打开文件写入文件数据
    with open(dst_file_path, "wb") as dst_file:
        # 打开源文件获取源文件数据
        with open(src_file_path, "rb") as src_file:
            # 循环读取文件中的数据
            while True:
                # 设置读取文件字节大小
                file_data = src_file.read(1024)
                if file_data:
                    # 把源文件的数据写入到目标文件里面
                    dst_file.write(file_data)
                else:
                    break


if __name__ == '__main__':

    # 指定源文件目录
    src_dir = "./test/"
    # 指定目标文件目录
    dst_dir = "../test/"

    # 判断目标是否存在该文件夹,存在则删除,并新建
    if os.path.exists(dst_dir):
      shutil.rmtree(dst_dir)
    os.mkdir(dst_dir)

    # 循环获源文件夹内容
    file_list = os.listdir(src_dir)

    # 创建进程池
    pool = multiprocessing.Pool(3)
    # 遍历文件名
    for file_name in file_list:
       # 异步写入文件操作
       pool.apply_async(copy_file, (file_name, src_dir, dst_dir))
    # 关闭进程池
    pool.close()
    # 设置阻塞主进程,等待当前进程执行完
    pool.join()

猜你喜欢

转载自blog.csdn.net/qq_30656253/article/details/79797264