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,
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With