How can we replace the whitespaces in the names of folders, subfolders and files in a given parent folder?
My initial attempt to replace up to level 8 is given below. I am sure there are better ways. My code looks ugly. Better solutions are more than welcome.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
def replace_space_by_underscore(path):
"""Replace whitespace in filenames by underscore."""
import glob
import os
for infile in glob.glob(path):
new = infile.replace(" ", "_")
try:
new = new.replace(",", "_")
except:
pass
try:
new = new.replace("&", "_and_")
except:
pass
try:
new = new.replace("-", "_")
except:
pass
if infile != new:
print(infile, "==> ", new)
os.rename(infile, new)
if __name__ == "__main__":
try:
replace_space_by_underscore('*/*/*/*/*/*/*/*')
except:
pass
try:
replace_space_by_underscore('*/*/*/*/*/*/*')
except:
pass
try:
replace_space_by_underscore('*/*/*/*/*/*')
except:
pass
try:
replace_space_by_underscore('*/*/*/*/*')
except:
pass
try:
replace_space_by_underscore('*/*/*/*')
except:
pass
try:
replace_space_by_underscore('*/*/*')
except:
pass
try:
replace_space_by_underscore('*/*')
except:
replace_space_by_underscore('*')