Skip to content
Advertisement

How can I delete multiple images from a folder using wildcards and a list of unique ids in a .txt file?

I am trying to delete about 3000 images from a folder with 5000 images. The image names look like this, for example: 03_38_25_006892_2.jpg

I have a .txt file that has the unique digits that follow the final underscore in the image name, for the images that I want to delete.

So the text file contents look maybe like this:

  • 2
  • 262
  • 278

And the corresponding files that should then be deleted from my folder are:

  • 03_38_25_006892_2.jpg
  • 03_38_42_463908_262.jpg
  • 03_38_44_015334_278.jpg

So far, I have only figured out how to delete one image at a time by giving the unique final digits. For that, I used successfully this code (using Python via JupyterLab on a Windows 10 PC):

import os
import glob

path = "C:L1/L2/L3/test3/*_2.jpg"
for file in glob.glob(path):
    os.remove(file)

But is there a way that I can make use of this .txt file I have to delete all the images at once from the folder?

Advertisement

Answer

Read the txt as a list using open("your_text.txt"), remove n on the end of the line using .rstrip(). Iterate to your function to delete the file.

import os
import glob

final_digits = [line.rstrip() for line in open("your_text.txt")]

for digit in final_digits:
    path = "C:L1/L2/L3/test3/*_{}.jpg".format(digit)
    for file in glob.glob(path):
        os.remove(file)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement