如何从文件夹中读取所有文本,并在其他文件夹python中保存与图像jpg文件同名的txt文件



我的文件夹中有ground-truth文本文件我的文件名是

Doc0006.Row1City.gt.txt

虽然我有图像文件名具有相同的ground truth文件Doc0006.Row1City.gt

Doc0006.Row1City0_rotate.jpg
Doc0006.Row1City1_rotate.jpg
Doc0006.Row1City2_rotate,jpg
Doc0006.Row1City3_rotate.jpg
Doc0006.Row1City4_rotate.jpg

我想在另一个文件夹中保存所有具有原始名称的图像的相同ground truth文件如何继续使用python

也许你可以这样做。我没有尝试过代码,因为我没有访问您的文件,但您可以根据您的需要更改或调整代码

import os
import shutil
ground_truth_folder_path = '' # add your folder path here
images_folder_path = '' # add your images path
new_folder_path = '' # the new folder with the files sorted
all_ground_truth_files = os.listdir(ground_truth_folder_path)
all_images_files = os.listdir(images_folder_path)
ground_truth_images = {}
for file in all_ground_truth_files:
ground_truth_images[file.replace(".gt.txt","")] = []
for file in all_images_files:
ground_truth_images[file[:16]].append(file)
for key, values in ground_truth_images.items():
new_folder_path_key = os.path.join(new_folder_path, key)
os.mkdir(new_folder_path_key)
shutil.copy(os.path.join(ground_truth_folder_path ,key+'.gt.txt'), os.path.join(new_file_path)
for file_name in values:
old_file_path = os.path.join(images_folder_path ,file_name)
new_file_path = os.path.join(new_folder_path_key, file_name)
shutil.copy(old_file_path , new_file_path)

最新更新