Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete multiple files matching a pattern

Tags:

python

I have made an online gallery using Python and Django. I've just started to add editing functionality, starting with a rotation. I use sorl.thumbnail to auto-generate thumbnails on demand.

When I edit the original file, I need to clean up all the thumbnails so new ones are generated. There are three or four of them per image (I have different ones for different occasions).

I could hard-code in the file-varients... But that's messy and if I change the way I do things, I'll need to revisit the code.

Ideally I'd like to do a regex-delete. In regex terms, all my originals are named like so:

^(?P<photo_id>\d+)\.jpg$ 

So I want to delete:

^(?P<photo_id>\d+)[^\d].*jpg$ 

(Where I replace photo_id with the ID I want to clean.)

like image 801
Oli Avatar asked Oct 10 '09 18:10

Oli


People also ask

How do you delete a pattern in Python?

To remove files by matching pattern, we need to get list of all files paths that matches the specified pattern using glob. glob() and then delete them one by one using os. remove() i.e.

How do I delete multiple files in Jupyter?

To delete multiple files, just loop over your list of files and use the above os. rmdir() function. To delete a folder containing all files you want to remove have to import shutil package.


2 Answers

Using the glob module:

import glob, os for f in glob.glob("P*.jpg"):     os.remove(f) 

Alternatively, using pathlib:

from pathlib import Path for p in Path(".").glob("P*.jpg"):     p.unlink() 
like image 74
Sam Bull Avatar answered Oct 01 '22 08:10

Sam Bull


Try something like this:

import os, re  def purge(dir, pattern):     for f in os.listdir(dir):         if re.search(pattern, f):             os.remove(os.path.join(dir, f)) 

Then you would pass the directory containing the files and the pattern you wish to match.

like image 23
Andrew Hare Avatar answered Oct 01 '22 06:10

Andrew Hare