# -*- coding:utf-8 -*- # @Author len # @Create 2023/10/12 10:00 import os import shutil # 源文件夹路径 txt_folder = r'D:\Code\Python\YOLO\datasets\coco128\labels\train2017' jpg_folder = r'D:\Code\Python\YOLO\datasets\coco128\images\train2017' # 目标文件夹路径 new_folder = r'D:\Code\Python\YOLO\datasets\coco128\new_folder' # 遍历txt文件夹中的所有txt文件 for filename in os.listdir(txt_folder): if filename.endswith('.txt'): file_path = os.path.join(txt_folder, filename) # 打开txt文件并查找指定内容 with open(file_path, 'r') as file: first_line = file.readline().strip() # 检查第一行内容的标签数字是否为0 if first_line.startswith('0'): # 获取对应的jpg文件名 print(file_path) jpg_filename = os.path.splitext(filename)[0] + '.jpg' jpg_path = os.path.join(jpg_folder, jpg_filename) # 移动jpg文件到新目录 new_path = os.path.join(new_folder, jpg_filename) shutil.copyfile(jpg_path, new_path) new_txt_path = os.path.join(new_folder, filename) shutil.copyfile(file_path, new_txt_path)