how to neglect case sensitivity in os.rename replace

Viewed 362

I have a script that replaces file names with a new filename that I specify, however, right now it is case sensitive (if a filename = DM, but I enter Dm, it is not being replaced)

I already tried filename.lower(), in the os.rename, but it doesn't seem to work. There are no errors though, that filename remains unaltered though.

import os

old = 'dm'
new = 'datamining'

path = os.getcwd()

filenames = os.listdir(path)
for filename in filenames:
    os.rename ( path+'\\'+ filename.lower() , path+'\\'+ filename.replace(old , new) )
1 Answers

Your actual file names are not necessarily in lowercase, but you're passing to the replace method a lowercase string of 'dm'. It cannot find the lowercase 'dm' in the file name and therefore returns the same file name, resulting in os.rename doing nothing.

You can lowercase the file name before you call the replace method instead:

os.rename( path+'\\'+ filename , path+'\\'+ filename.lower().replace(old , new) )

This will force the new file name to be entirely in lowercase, however. If you want to preserve the casing of the rest of the file names, you can use re.sub with the IGNORECASE flag instead:

import re

...

os.rename( path+'\\'+ filename , path+'\\'+ re.sub(old, new, filename, flags=re.IGNORECASE))
Related