1.代码实现功能,根据txt文件名并批量提取出对应文件名中的图片 2.根据image的名称批量提取对应文件的txt文件名

博客围绕深度学习和人工智能展开,强调了Python在其中的作用。Python作为重要工具,在深度学习和人工智能领域能发挥关键效能,推动相关技术的发展与应用。
# srcfile 需要复制、移动的文件
# dstpath 目的地址
# 代码实现功能,根据txt文件名提取并提取出对应文件名的图片
# 根据images图片名提取并提出对应的txt文件名
import os
import shutil
from glob import glob
def mycopyfile(srcfile, dstpath):  # 复制函数
    if not os.path.isfile(srcfile):
        print("%s not exist!" % (srcfile))
    else:
        fpath, fname = os.path.split(srcfile)  # 分离文件名和路径
        if not os.path.exists(dstpath):
            os.makedirs(dstpath)  # 创建路径
        shutil.copy(srcfile, dstpath + fname)  # 复制文件
        print("copy %s -> %s" % (srcfile, dstpath + fname))



src_dir = r'C:\Users\yewenjing\Desktop\简化标签\all_labels/'  # 要提取对应图片的文件夹路径  or  txt提取
dst_dir = r'C:\Users\yewenjing\Desktop\1023train\upgrade_images_train/'  # 目的路径记得加斜杠 保存的地址
txt_path = r'C:\Users\yewenjing\Desktop\1023train\upgrade_images_train'     # txt文件名提取 or jpg图片提取
name=[]
# with open(txt_path) as f1:
txt_names = os.listdir(txt_path)
for i in range(len(txt_names)):
    # per_txt_path=os.path.join(txt_path,txt_names[i].split(".txt")[0]+".txt")
    # name.append(txt_names[i].split(".txt")[0])   # 提取txt文件名
    name.append(txt_names[i].split(".jpg")[0])   # 提取jpg文件名


src_file_list=[]
for imges_all in name:
    # src_file_list.append(src_dir+imges_all+".jpg")  #提取图片对应的jpg文件
    src_file_list.append(src_dir+imges_all+".txt")  #提取图片对应的txt文件
# print(src_file_list)
for srcfile in src_file_list:
    mycopyfile(srcfile, dst_dir)  # 复制文件

可以使用Python中的文件操作和正则表达式来实现这个功能。 首先,你需要读取txt文档中的ID号,可以使用Python中的`open()`函数来打开文件,然后使用`readlines()`函数将文件内容按行读取到一个列表中。 接着,你需要批量提取文件夹中对应ID号的图像,可以使用Python中的`os`模块来实现文件夹操作。具体步骤如下: 1. 使用`os.listdir()`函数获取文件夹中所有文件文件名列表。 2. 使用正则表达式匹配每个文件名提取文件名中的ID号。 3. 判断该ID号是否在读取txt文档中,如果在,则将该文件复制到指定的目录中。 下面是一个示例代码,供你参考: ```python import os import re import shutil # 定义txt文件路径、图像文件夹路径、输文件夹路径 txt_path = "id_list.txt" img_folder = "image_folder" output_folder = "output_folder" # 读取txt文件中的ID号列表 with open(txt_path, "r") as f: id_list = [line.strip() for line in f.readlines()] # 遍历图像文件中的所有文件 for filename in os.listdir(img_folder): # 使用正则表达式匹配文件名中的ID号 match = re.search(r"\d+", filename) if match: id = match.group() # 判断该ID号是否在txt文件中 if id in id_list: # 如果在,则将该文件复制到输文件夹中 src_path = os.path.join(img_folder, filename) dst_path = os.path.join(output_folder, filename) shutil.copyfile(src_path, dst_path) ``` 以上代码中,我们使用了正则表达式`\d+`来匹配文件名中的数字部分,然后使用了`shutil.copyfile()`函数来复制文件。你可以根据自己的需求修改文件路径和正则表达式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值