I kindly ask for guidance or support on how to approach coding a Python script to remove .jpg images without.txt files. Presently, I have a train folder with folders images and labels. I am planning to put the images and their matching txt files in a directory. There are 70000 images and 69863 txt files with labels. I need to remove those images without their matching txt files, so I can have the same number of images as well as txt files. That is 69863 images matching those 69863 txt files.

An example is as follows: the image 0b911639-98f93d75.jpg has its txt file 0b911639-98f93d75.txt. However, some images have missing txt files. Thank you in advance!

2 Answers 2


I've created dirs tree like this:

├── images
│   ├── 1.jpg
│   ├── 2.jpg
│   ├── 3.jpg
│   ├── 4.jpg
│   └── 5.jpg
└── labels
    ├── 1.txt
    ├── 2.txt
    └── 5.txt

Easiest way to do it:

from os import listdir, remove
labels = listdir('labels')
images = listdir('images')
for image in images:
 if '{}.{}'.format(image.split('.')[0], 'txt') not in labels:
  print('Going to remove %s' % image)
  remove('images/%s' % image)
  • Thank you! I will let you know the results later. Jul 7, 2019 at 6:16

You can do it with a simple for loop from within the images folder:

cd images
for f in *.jpg; do [ -f "../labels/${f%.*}.txt" ] || echo rm "$f"; done

Remove the echo if you're happy with the output.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .