Python 多进程拷贝文件夹案例

import os
import multiprocessing


def copy_file(q, file_name, old_folder_name, new_folder_name):
    """ 完成文件的复制 """
    old_file = open(old_folder_name + "/" + file_name, "rb")
    content = old_file.read()
    old_file.close()

    new_file = open(new_folder_name + "/" + file_name, "wb")
    new_file.write(content)
    new_file.close()
    q.put(file_name)


def main():
    # 获取用户要copy 文件夹的名字
    old_folder_name = input("请输入要copy的文件夹的名字:")
    # 创建一个新文件夹
    new_folder_name = old_folder_name + "2"
    os.mkdir(new_folder_name)
    # 获取文件夹的所有的待copy的文件名字  listdir()
    file_names = os.listdir(old_folder_name)
    print(file_names)
    # 4. 创建进程池
    po = multiprocessing.Pool(5)
    # 5. 创建一个队列
    # manager = multiprocessing.Manager() 可以创建一个Manger对象
    q = multiprocessing.Manager().Queue()
    # 6. 向进程池中添加 copy文件的任务
    for file_name in file_names:
        po.apply_async(copy_file, args=(q, file_name, old_folder_name, new_folder_name))
    po.close()
    # po.join()
    all_file_name = len(file_names)
    copy_ok_file = 0
    while True:
        file_name = q.get()
        copy_ok_file += 1
        print("\r拷贝进度为:%0.2f%%" % (copy_ok_file * 100 / all_file_name), end="")
        if copy_ok_file >= all_file_name:
            break


if __name__ == '__main__':
    main()

 

转载于:https://www.cnblogs.com/duxie/p/11336585.html

你可能感兴趣的:(Python 多进程拷贝文件夹案例)