0

I'm using the following function to remove a specific string pattern from files in a directory:

import os
for filename in os.listdir(path):
   os.rename(filename, filename.replace(r'^[A-Z]\d\d\s-\s[A-Z]\d\d\s-\s$', ''))

The pattern is as follows, where A is any capital letter, and # is any number between 0-9:

A## - A## -

My regex matches this format on regex101. When I run the above function, it completes without error, however no directory names change. Where am I going wrong?

Laurie
  • 1,189
  • 1
  • 12
  • 28

2 Answers2

3

replace string method does not support regular expressions.

You need to import the re module and use its sub method.

So your code might look like this:

import os
import re
for filename in os.listdir(path):
   os.rename(filename, re.sub(r'^[A-Z]\d\d\s-\s[A-Z]\d\d\s-\s', '', filename))

But don't forget about flags and such.

Edit: Removed $ from the pattern as the filenames don't end there.

Chillie
  • 1,356
  • 13
  • 16
  • Odd, I've tried this but it's still not working for some reason, it completes without error however nothings changed. – Laurie Sep 14 '18 at 16:05
  • 1
    @LaurieBamber could you give us a couple sample filenames? – Chillie Sep 14 '18 at 16:07
  • File 1: 'S01 - E01 - Something Here', File 2: 'S01 - E02 - Something Different'.... File k: 'S07 - E06 - Something Different' – Laurie Sep 14 '18 at 16:08
  • 1
    @LaurieBamber You have the string end marker (`$`) in your pattern, but the file name does not end there, so it doesn't match. Just remove the `$` from your pattern. – Chillie Sep 14 '18 at 16:09
  • Gentleman, thats done it. Thanks for the help. – Laurie Sep 14 '18 at 16:10
  • 1
    @LaurieBamber Happy to help. Don't forget to mark the question as solved (answer as accepted). =) – Chillie Sep 14 '18 at 16:15
1
import re
filename='A11 - A22 - '#A## - A## -
re.sub(filename,r'^[A-Z]\d\d\s-\s[A-Z]\d\d\s-\s', '')
mad_
  • 8,121
  • 2
  • 25
  • 40