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

2024-09-28 05:19:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有地面真相文本文件在文件夹中我的文件名是

Doc0006.Row1City.gt.txt

而我的图像文件名具有相同的基本事实文件Doc0006.Row1City.gt

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

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


Tags: 文件图像gttxt文件夹文件名事实jpg
1条回答
网友
1楼 · 发布于 2024-09-28 05:19:52

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

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)

相关问题 更多 >

    热门问题