Skip to content

Instantly share code, notes, and snippets.

@icefo
Created April 30, 2021 12:52
Show Gist options
  • Save icefo/70a85b44c9536bff10c4a335603faa55 to your computer and use it in GitHub Desktop.
Save icefo/70a85b44c9536bff10c4a335603faa55 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import os
to_replace = ":"
replace_by = " "
DRY_RUN = False
for (dirpath, dirnames, filenames) in os.walk("/root/of/path", topdown=False):
if DRY_RUN:
print("DRY RUN ", end="")
print(f"Current folder: {dirpath}")
for filename in filenames:
new_name = filename
if to_replace in filename:
new_name = filename.replace(to_replace, replace_by)
# remove leading and trailing spaces and limit to one consecutive space
split_string = new_name.split(' ')
new_name = ' '.join(item for item in split_string if item)
if filename != new_name:
print(f" Renamed file \"{filename}\" to \"{new_name}\"")
if not DRY_RUN:
os.rename(os.path.join(dirpath, filename), os.path.join(dirpath, new_name))
for dirname in dirnames:
new_name = dirname
if to_replace in dirname:
new_name = dirname.replace(to_replace, replace_by)
# remove leading and trailing spaces and limit to one consecutive space
split_string = new_name.split(' ')
new_name = ' '.join(item for item in split_string if item)
if dirname != new_name:
print(f" Renamed dir \"{dirname}\" to \"{new_name}\"")
if not DRY_RUN:
os.rename(os.path.join(dirpath, dirname), os.path.join(dirpath, new_name))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment