本文主要是介绍将jpg图片和txt标签文件重新命名,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
处理文件夹里面jpg图片的名字
将文件夹里面的jpg图片重新命名
import osdirectory = 'C:\\Users\\23608\\Desktop\\Luli_work\\data\\fanStudent\\dataset'
i = 1
for file in os.listdir(directory):if file.endswith('.jpg'):old_name = os.path.basename(file).split('.')[0]new_name = f'{i}.jpg'old_path = os.path.join(directory, f"{old_name}.jpg")new_path = os.path.join(directory, new_name)os.rename(old_path, new_path)i += 1
将jpg图片和txt标签文件重新命名
适用于,将jpg对应的标签文件同时改一下名字,保持一致。
jpg图片的路径:/path/to/jpg
txt文件的路径:/path/to/txt
import os
import shutil# 原始文件夹路径
image_folder_path = '/path/to/jpg'
label_folder_path = '/path/to/txt'# 新文件夹路径
new_image_folder_path = r'C:\Users\23608\new_jpg'
new_label_folder_path = r'C:\Users\23608\new_txt'# 创建新文件夹
os.makedirs(new_image_folder_path, exist_ok=True)
os.makedirs(new_label_folder_path, exist_ok=True)num = 1
#遍历原始文件夹
for file in os.listdir(image_folder_path):num = num + 1if file.endswith('.jpg'):filename = os.path.basename(file).split('.')[0]# print(filename)# 构造新文件名new_image_name = f"{num}.jpg"new_label_name = f"{num}.txt"print(new_image_name, new_label_name)#构造文件路径old_image_path = os.path.join(image_folder_path, f'{filename}.jpg')# print(old_image_path)old_label_path = os.path.join(label_folder_path, f'{filename}.txt')# print(old_label_path)new_image_path = os.path.join(new_image_folder_path, new_image_name)# print(new_image_path)new_label_path = os.path.join(new_label_folder_path, new_label_name)# print(new_label_path)# 复制并重命名图片shutil.copy(old_image_path, new_image_path)# 复制并重命名标签文件shutil.copy(old_label_path, new_label_path)
print("重命名完成。")
这篇关于将jpg图片和txt标签文件重新命名的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!