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?

0

2 Answers 2

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.

6
  • Odd, I've tried this but it's still not working for some reason, it completes without error however nothings changed.
    – Laurie
    Commented Sep 14, 2018 at 16:05
  • 1
    @LaurieBamber could you give us a couple sample filenames?
    – Chillie
    Commented Sep 14, 2018 at 16:07
  • File 1: 'S01 - E01 - Something Here', File 2: 'S01 - E02 - Something Different'.... File k: 'S07 - E06 - Something Different'
    – Laurie
    Commented Sep 14, 2018 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
    Commented Sep 14, 2018 at 16:09
  • 1
    @LaurieBamber Happy to help. Don't forget to mark the question as solved (answer as accepted). =)
    – Chillie
    Commented Sep 14, 2018 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', '')
3
  • Thanks, this still isn't working for some reason with my code though.
    – Laurie
    Commented Sep 14, 2018 at 16:07
  • 1
    can you print the output after executing the above code?
    – mad_
    Commented Sep 14, 2018 at 16:09
  • My mistake, as pointed out by Chillie I was incorrectly using the $ symbol to finish the pattern. Thanks for the help anyway.
    – Laurie
    Commented Sep 14, 2018 at 16:11

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.