【问题标题】:How to read all text from folder and save txt file with same name as image jpg file in other folder python如何从文件夹中读取所有文本并将与图像jpg文件同名的txt文件保存在其他文件夹python中
【发布时间】:2021-08-19 15:52:25
【问题描述】:

我的文件名所在的文件夹中有真实文本文件

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

【问题讨论】:

    标签: python python-3.x opencv text-files glob


    【解决方案1】:

    也许您可以执行以下操作。我没有尝试过代码,因为我无权访问您的文件,但您可以根据需要更改或调整代码

    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)
    
    

    【讨论】:

    • 我的图像在一个文件夹中,ground truth.txt 文件在另一个文件夹中,我可以在这里共享图像代码不起作用``` NameError: name 'ground_truth' is not defined ```跨度>
    • 我已经编辑了答案,但请记住我没有测试过代码。我建议您尝试理解代码并对其进行更改以使其正常工作。学习一门新语言一开始似乎很难,但最终它是一种可以理解的语言。
    • 谢谢我收到错误 KeyError Traceback(最近一次调用最后一次) in 11 12 for file in all_images_files: ---> 13 ground_truth_images[file[ :16]].append(file) 14 15 用于键,ground_truth_images.items() 中的值:KeyError: 'Doc0006.Row1City'
    猜你喜欢
    • 2021-10-20
    • 2017-10-29
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 2011-08-20
    • 2021-08-31
    相关资源
    最近更新 更多