python批量复制指定txt中的图片到指定文件夹

import os
import shutil

f = open(r'D:\VOC2007\ImageSets\Main\test.txt', 'r')# 打开保存图片的txt,只有名字,不带jpg
lines = f.readlines()

root_path = 'D:/VOC2007/JPEGImages'  # 待复制图像所在文件夹路径
obj_path = 'E:/dangyuan/mmdetection-2.27.0/data/coco/test2017'  # 目标文件夹路径
filelist = os.listdir(root_path)

for item in filelist:  # 遍历所有图片,找到对应的图片并复制
    for line in lines:
        line = line.replace('\n', '')
        lineo = str(line) +".jpg"
       
        if lineo == item:  # 复制图像个数

            src = os.path.join(os.path.abspath(root_path), lineo)
            dst = os.path.join(os.path.abspath(obj_path), item)
            shutil.copy(src, dst)  # 将src复制到dst
            
print('ending...')