Skip to content

Instantly share code, notes, and snippets.

@davidlanouette
Created April 26, 2024 20:22
Show Gist options
  • Save davidlanouette/a598c525e1212f005bc889da057b884a to your computer and use it in GitHub Desktop.
Save davidlanouette/a598c525e1212f005bc889da057b884a to your computer and use it in GitHub Desktop.
Rename files with "illegal" characters. All illegal chars get replaced with either a "-", or removed.
#!/usr/bin/env python3
import sys
import os
DEBUGGING = False
DRY_RUN = False
if (len(sys.argv) > 1):
print(f"First arg is {sys.argv[1]}")
target_path = sys.argv[1]
else:
target_path = os.getcwd()
print(f"First arg is blank. Using {target_path}")
def debug(msg):
if DEBUGGING:
print(msg)
def should_be_renamed(f):
extensionsToCheck = ['/', '\\', '?', ':', '*', '"', '<', '>', '|']
return any(str in f for str in extensionsToCheck)
def rename_file(file_name, path):
new_file_name = (
file_name.replace('/', '-').replace('\\', '-').replace('?', '-').replace(':', '-').replace('*', '-').
replace('"', '').replace('<', '-').replace('>', '-').replace('|', '-'))
debug('')
debug(f"{file_name=}")
if file_name == new_file_name:
print('name unchanged: ' + file_name)
else:
if DRY_RUN:
print(f"DRYRUN: Would have renamed {os.path.join(path, file_name)} to {os.path.join(path, new_file_name)}")
else:
print(f"Renaming {os.path.join(path, file_name)} to {os.path.join(path, new_file_name)}")
os.rename(os.path.join(path, file_name), os.path.join(path, new_file_name))
def clean_files(path):
if (os.path.exists(path)):
for root, dir_names, file_names in os.walk(path):
for file_name in file_names:
debug(f"{root=}, {file_name=}")
debug(f"checking if file '{file_name}' should be renamed")
if should_be_renamed(file_name):
debug(f"file '{file_name}' needs to be renamed")
rename_file(file_name, root)
for dir_name in dir_names:
debug(f"{root=}, {dir_name=}")
debug(f"checking if dir '{dir_name}' should be renamed")
if should_be_renamed(dir_name):
debug(f"dir '{dir_name}' needs to be renamed")
rename_file(dir_name, root)
if __name__ == '__main__':
clean_files(os.path.expanduser(target_path))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment