Tom
Tom

Reputation: 39

Delete files in python that contain a number anywhere in the file name

I have a directory containing .jpg files and I need to delete all files within this directory containing a number anywhere in the file name.

I've used os.listdir to specify the path. I was then able to use fnmatch.fnmatch to only delete something specific like "3453.jpg", but I need it to delete something like thomas9.jpg or thom43as.jpg. Basically any file name containing a number needs to be deleted.

Thanks, Tom

Upvotes: 2

Views: 4327

Answers (3)

Kenly
Kenly

Reputation: 26698

Use re module.

import os
import re


for _file in os.listdir('.'):
    if re.search('\d.*\.jpg$', _file):
        print(_file)

Upvotes: 3

mhawke
mhawke

Reputation: 87074

Using glob()/iglob() is slightly easier than using a regex:

import glob
import os

def delete_files(path, pattern):
    for f in glob.iglob(os.path.join(path, pattern)):
        try:
            os.remove(f)
        except OSError as exc:
            print exc

>>> delete_files('/tmp', '*[0-9]*.jpg')

os.remove() should be called within a try/except block in case the file can not be removed, e.g. insufficient permissions, in use by another process, the file is a directory etc.

Using regex, if there are many files it could be worth compiling the pattern outside of the loop:

import os
import re

def delete_files(path, pattern):
    pattern = re.compile(pattern)
    for f in os.listdir(path):
        if pattern.search(f):
            try:
                os.remove(os.path.join(path, f))
            except OSError as exc:
                print exc

delete_files('/tmp', r'\d.*\.jpg$')

Upvotes: 2

Iron Fist
Iron Fist

Reputation: 10951

regex is not really necessary in your case, if you want to delete any file with filename containing any digits, then you can do it simply this way:

import os

my_path = 'path_to_your_directory'
any_digit = '1234567890'

os.chdir(my_path) #Just to be sure you are in your working directory not else where!

for f in os.listdir('.'):
    if any(x in f for x in any_digit) and f.endswith('.jpg'):
        os.remove(f)

You can also use string module and then:

import os
import string

my_path = 'path_to_your_directory'

os.chdir(my_path) #Just to be sure you are in your working directory not else where!

for f in os.listdir('.'):
    if any(x in f for x in string.digits) and f.endswith('.jpg'):
        os.remove(f)

Upvotes: 2

Related Questions