python 线程池处理文件

发布于:2024-08-01 ⋅ 阅读:(91) ⋅ 点赞:(0)

使用多线程来加速文件复制的过程,可以使用Python的concurrent.futures模块中的ThreadPoolExecutor。代码如下:



import glob
import os
import shutil
from concurrent.futures import ThreadPoolExecutor


def copy_image(image):
    imagepath = image.replace("\\", "/")
    # 假设文件名格式为:xxx_yyy.jpg,其中xxx是我们想要的部分,yyy是日期或编号
    # 我们只取文件名中的xxx和扩展名.jpg,并用目录名替换掉日期或编号
    imagename = imagepath.split('/')[-1].split('_')[0] + "_" + imagepath.split('/')[-2].split('.')[-1]
    new_path = os.path.join('image', imagename + '.jpg')
    shutil.copy(imagepath, new_path)
    print(imagepath)


def main():
    img_list = glob.glob('D:/911/*/*.jpg')
    os.makedirs('image', exist_ok=True)

    # 使用 ThreadPoolExecutor 来并行处理文件复制
    with ThreadPoolExecutor(max_workers=20) as executor:  # 可以调整max_workers的数量以适应你的CPU和IO性能
        executor.map(copy_image, img_list)


if __name__ == "__main__":
    main()

为了使用多线程来加速文件复制的过程,你可以使用Python的concurrent.futures模块中的ThreadPoolExecutor。这个模块允许你轻松地并行执行多个任务。以下是你的代码的多线程版本:

import glob
import os
import shutil
from concurrent.futures import ThreadPoolExecutor

def copy_image(image):
    imagepath = image.replace("\\", "/")
    # 假设文件名格式为:xxx_yyy.jpg,其中xxx是我们想要的部分,yyy是日期或编号
    # 我们只取文件名中的xxx和扩展名.jpg,并用目录名替换掉日期或编号
    imagename = imagepath.split('/')[-1].split('_')[0] + "_" + imagepath.split('/')[-2].split('.')[-1]
    new_path = os.path.join('image', imagename + '.jpg')
    shutil.copy(imagepath, new_path)

def main():
    img_list = glob.glob('D:/caohejing_20240711/*/*.jpg')
    os.makedirs('image', exist_ok=True)

    # 使用 ThreadPoolExecutor 来并行处理文件复制
    with ThreadPoolExecutor(max_workers=10) as executor:  # 可以调整max_workers的数量以适应你的CPU和IO性能
        executor.map(copy_image, img_list)

if __name__ == "__main__":
    main()

代码说明:

  1. 函数copy_image:这个函数接受一个图片路径作为参数,然后执行复制操作。它首先修改路径分隔符,然后解析文件名并构建新的文件名和路径,最后使用shutil.copy复制文件。

  2. 函数main:这是主函数,它首先获取所有图片的路径,然后创建一个名为image的目录(如果它不存在的话)。之后,它使用ThreadPoolExecutor来并行地执行copy_image函数,其中executor.map类似于map函数,但是它会并行地应用给定的函数到可迭代对象中的每个元素。

  3. __name__ == "__main__":这是Python的标准做法,用来判断该脚本是直接运行还是被导入到其他脚本中作为模块。直接运行时,会执行main函数。

  4. max_workers:这是ThreadPoolExecutor的一个参数,它决定了线程池中的线程数量。你可以根据你的CPU核心数和IO操作的需求来调整这个值。在这个例子中,我使用了10,但你应该根据你的具体环境来设置这个值。

注意:虽然多线程可以提高IO密集型任务的效率,但每个线程的创建和销毁都需要一定的开销。此外,由于Python的全局解释器锁(GIL),多线程在CPU密集型任务上可能不会带来太大的性能提升。然而,对于文件复制这样的IO密集型任务,多线程是非常有用的。

多线程修改json文件

import json
import glob
from concurrent.futures import ThreadPoolExecutor

labelme_path = "../Labelme_data/"


# 定义一个函数来处理单个文件
def process_file(file_path):
    with open(file_path, "r", encoding="utf-8") as f:
        json_file = json.load(f)
    shapes = json_file['shapes']
    print(shapes)
    for shape in shapes:
        if shape['label'] == 'f16':
            shape['label'] = 'person'
        elif shape['label'] == 'f35':
            shape['label'] = 'other'
    with open(file_path, 'w') as f:
        json.dump(json_file, f, indent=4)

    # 3. 获取待处理文件


files = glob.glob(labelme_path + "*.json")

# 使用ThreadPoolExecutor来并行处理文件
with ThreadPoolExecutor(max_workers=40) as executor:  # 可以根据机器性能调整max_workers
    executor.map(process_file, files)

print("所有文件处理完成。")