Move the picture with the corresponding name according to the file name

For example, I have a bunch of files with txt suffix, as shown in the figure below,
insert image description here
I need to find the pictures corresponding to these txt, use the following code

import os

images_dir = r'VOCdevkit/VOC2007/JPEGImages'#图片的位置
txt_dir = r'D:\GoogleDownload\python_project_file\yolov4-tiny-keras-voc\map_out\ground-truth'#txt文件的位置
import shutil
# 创建列表
txts = []
# 读取xml文件名(即:标注的图片名)
for txt in os.listdir(txt_dir):
    # xmls.append(os.path.splitext(xml)[0])    #append()参数:在列表末尾添加新的对象,即将所有文件名读入列表
    txts.append(txt.split('.txt')[0])  # splitext和split的区别:前者('0001','.jpg'), 后者('0001','jpg') 在此可选用
    # xmls.append(xml)
print(txts)
# 读取所有图片
for image_name in os.listdir(images_dir):
    print("1111",image_name)
    image_name = image_name.split('.')[0]
    print('2222',image_name)
    if image_name in txts:
        image_name = image_name + '.JPG'
        print('3333',image_name)
        shutil.move(os.path.join(images_dir, image_name),'新建文件夹')

After running, you can move the picture to the specified folder
insert image description here

Guess you like

Origin blog.csdn.net/weixin_43850171/article/details/123227276