Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python recursively rename directories

I made a script to rename directories with a name that contains spaces or special characters recursively:

import os
import re
import pdb

def renameInvalid(root):
    print("root is: " + root)
    for f in os.listdir(root):        
        if os.path.isdir(f):            
            old = f
            f = f.replace(" ", "_")
            f = re.sub(r'[^a-zA-Z0-9-_]', '',f)
            if old != f:
                print(root + " na substitutie")
                os.rename(old,f)
                print(root + " na hernoemen")
                print("renamed " + old + " to " + f )
                #pdb.set_trace() 
                f = '/' + f
                pad = root + f                
                renameInvalid(str(pad))

mountpunt = os.getcwd()
renameInvalid(mountpunt)

You can test this script by making two directories with names containing spaces. You place one of the directories inside the other and run the script from inside the first directory. The script renames the first directory but generates an OSError on isdir(f). Does anyone know what is the problem here?

Regards,

like image 766
Reginald Carlier Avatar asked Feb 21 '26 19:02

Reginald Carlier


1 Answers

I found the answer (thanks to timbaileyjones for his solution).

import os
import re

def renameInvalid(root):    
    for f in os.listdir(root):        
        old = f
        f = f.replace(" ", "_")
        f = re.sub(r'[^a-zA-Z0-9-_]', '',f)
        if old != f:                              
                os.rename(old,f)                
                print("renamed " + old + " to " + f )
        if os.path.isdir(f):
            os.chdir(f)
            renameInvalid(".")
            os.chdir("..")            

renameInvalid(".")

One should only run this code if they know what they are doing. It renames all the folders and files with whitespace or special characters in the filename.

Regards,

like image 65
Reginald Carlier Avatar answered Feb 23 '26 09:02

Reginald Carlier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!