Search code examples
pythonregexrenamefile-renameregexp-replace

Python rename file - replace all underscores with space


I am using python to rename all files in a directory with extension ".ext". The script is in the same folder as the files so no need to worry about path.

How to replace all underscores in filenames with spaces? For example filename This_is_a_file 01 v2.22.ext to This is a file 01 v2.22.ext? I have tried the below code:

import glob, re, os

for filename in glob.glob('*.ext'):
    new_name = re.sub("_", " ", filename) # this line does work
    os.rename(filename, new_name)

Edit: Sorry, I had a logic error elsewhere in my code. There were more replacement lines than I showed here but I was assigning new_name to replacements of filename instead of updating new_name at each step. The above code should work.


Solution

  • You could try something like this:

     import glob, re, os
    
     for filename in glob.glob('*.ext'):
        new_name = ' '.join(filename.split('_'))  # another method 
        os.rename(filename, new_name)
    

    Cheers