1

I am trying to remove files from a folder matching a specific pattern and running into below error, how to fix this error?

import os,re,shutil
def purge(dir, pattern):
    for f in os.listdir(dir):
        print f,pattern
        if re.search(pattern, f):
            os.remove(os.path.join(dir, f))
dir = '/home/username/chip/com/output/usr/share/firmware/tech/C-1234__s-B2/debug'
patterns =['*.map','*.map-sym-details','*logstrs.bin','*.exe','*.dis']
for pattern in patterns:
        purge(dir,pattern)

Error:-

Traceback (most recent call last):
  File "files_to_remove.py", line 20, in <module>
    purge(dir,pattern)
  File "files_to_remove.py", line 5, in purge
    if re.search(pattern, f):
  File "/usr/local/lib/python2.7/re.py", line 146, in search
    return _compile(pattern, flags).search(string)
  File "/usr/local/lib/python2.7/re.py", line 251, in _compile
    raise error, v # invalid expression
sre_constants.error: nothing to repeat  
user3508811
  • 847
  • 4
  • 19
  • 43
  • 1
    `'*.map'` is not a valid regular expression. It looks more like a `glob` wildcard. – Patrick Haugh Aug 06 '18 at 02:09
  • @PatrickHaugh - how to fix the error then? – user3508811 Aug 06 '18 at 02:11
  • I changed to `if re.search(glob.glob(pattern), f):` which throws a type error `File "files_to_remove.py", line 5, in purge if re.search(glob.glob(pattern), f): File "/usr/local/lib/python2.7/re.py", line 146, in search return _compile(pattern, flags).search(string) File "/usr/local/lib/python2.7/re.py", line 237, in _compile p, loc = _cache[cachekey] TypeError: unhashable type: 'list'` – user3508811 Aug 06 '18 at 02:15
  • Remove the `listdir` and the `re.search`, just use the glob. I added a second duplicate, read it too. – Stephen Rauch Aug 06 '18 at 02:16
  • @StephenRauch - how would you loop through every file in the dir if I remove listdir,do you mind being more specific? – user3508811 Aug 06 '18 at 02:19
  • Go read... especially things like: https://docs.python.org/3/library/glob.html#glob.glob If these do not make sense ask a new targeted question. – Stephen Rauch Aug 06 '18 at 02:20

0 Answers0