根据.txt文件读取文件名(无后缀)相同的图片(.jpg)和标签(.txt)并保存到相应的文件夹里

import os
import shutil

input_dir = "dataset"
output_dir = "output"
matching_folder = "matched_files"
unmatching_folder = "unmatched_files"
file_names_file = os.path.join(input_dir, "file_names.txt")

# 创建输出文件夹
output_matching_dir = os.path.join(output_dir, matching_folder)
output_unmatching_dir = os.path.join(output_dir, unmatching_folder)
os.makedirs(output_matching_dir, exist_ok=True)
os.makedirs(output_unmatching_dir, exist_ok=True)

# 读取文件名列表
with open(file_names_file, "r") as f:
    file_names = [line.strip() for line in f]

# 遍历文件名列表
for file_name in file_names:
    image_path = os.path.join(input_dir, "images", file_name + ".jpg")
    label_path = os.path.join(input_dir, "labels", file_name + ".txt")

    # 如果图片和标签文件都存在,将它们移动到匹配文件夹
    if os.path.exists(image_path) and os.path.exists(label_path):
        shutil.copyfile(image_path, os.path.join(output_matching_dir, file_name + ".jpg"))
        shutil.copyfile(label_path, os.path.join(output_matching_dir, file_name + ".txt"))
    else:
        print(f"未找到匹配文件: {file_name}")

print("文件移动完成!")

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值