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.

Sign up to request clarification or add additional context in comments.

6 Comments

Odd, I've tried this but it's still not working for some reason, it completes without error however nothings changed.
@LaurieBamber could you give us a couple sample filenames?
File 1: 'S01 - E01 - Something Here', File 2: 'S01 - E02 - Something Different'.... File k: 'S07 - E06 - Something Different'
@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.
@LaurieBamber Happy to help. Don't forget to mark the question as solved (answer as accepted). =)
|
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 Comments

Thanks, this still isn't working for some reason with my code though.
can you print the output after executing the above code?
My mistake, as pointed out by Chillie I was incorrectly using the $ symbol to finish the pattern. Thanks for the help anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.