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.)
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.
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.
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With