Skip to content

Instantly share code, notes, and snippets.

@jbfriedrich
Created April 18, 2022 16:10
Show Gist options
  • Save jbfriedrich/b9b671943dd0f1ee3e15c7ebb32524d1 to your computer and use it in GitHub Desktop.
Save jbfriedrich/b9b671943dd0f1ee3e15c7ebb32524d1 to your computer and use it in GitHub Desktop.
Remove unsafe and unwanted character from Audible flac/mp3 export
#!/usr/bin/env python3
import os
import re
def replace(basepath, item):
"""
Replace unsafe character from items
"""
replacements = {
" ": "_",
":": "_-_",
"/": "_-_",
",": "_",
"'": "",
"__": "_",
}
sanitized_name = None
for pattern, replacement in replacements.items():
if sanitized_name is None:
temp_name = re.sub(pattern, replacement, item)
else:
temp_name = re.sub(pattern, replacement, temp_name)
sanitized_name = temp_name
old_dir = os.path.join(basepath, item)
new_dir = os.path.join(basepath, sanitized_name)
print(f'Rename "{old_dir} to "{new_dir}"')
os.rename(old_dir, new_dir)
def main():
"""
Go recursively through the filesystem and safely rename
all the files and directories
"""
path = '.'
for basepath, directories, files in os.walk(path, topdown=False):
for file in files:
replace(basepath, file)
for directory in directories:
replace(basepath, directory)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment