在平时工作中我们可能会遇到需要进行文件转储的情况,如果需要复制的文件比较多,在图形界面上进行复制会消耗大量的时间。为了解决以上问题,我们可以利用几行python代码实现文件的多线程转储,加快文件的转储速度。
代码
import os
import shutil
from concurrent.futures import ThreadPoolExecutor
# 源文件夹路径
source_dir = "detection/downloaded_images_jpg"
# 目标文件夹路径
target_dir = "data/downloaded_images_jpg"
# 确保目标文件夹存在,如果不存在则创建
os.makedirs(target_dir, exist_ok=True)
def move_file(file_name):
""" 移动单个文件的函数 """
source_file = os.path.join(source_dir, file_name)
target_file = os.path.join(target_dir, file_name)
# shutil.move(source_file, target_file)
shutil.copy(source_file, target_file)
return f"文件 {file_name} 移动完成。"
# 使用 ThreadPoolExecutor 来创建线程池
with ThreadPoolExecutor(max_workers=50) as executor:
# 获取源文件夹中的所有文件名
files = os.listdir(source_dir)
# 为每个文件启动一个线程
results = executor.map(move_file, files)
# 输出结果
for result in results:
print(result)
print("所有文件已成功移动。")
通过以上代码,我们就可以对大量文件进行转储了,希望对大家有帮助!