Created
February 28, 2020 17:16
-
-
Save gmolveau/639121cdcd550a628dd9d2076e4d3c7c to your computer and use it in GitHub Desktop.
Python3 file and folder/directory sanitizer/format/renamer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os, re, unicodedata | |
def clean(input_str): | |
# remove accents, only_ascii | |
nfkd_form = unicodedata.normalize('NFKD', input_str) | |
only_ascii = nfkd_form.encode('ASCII', 'ignore') | |
name = str(only_ascii, 'utf-8') | |
# replace non alphanumeric caracters by underscore | |
name = re.sub('[^0-9a-zA-Z]+', '_', name) | |
return name | |
def clean_file(name, path): | |
s = os.path.splitext(name) | |
filename, extension = s[0], s[1] | |
clean_file = clean(filename) | |
base = os.path.dirname(path) | |
new_file = os.path.join(base, clean_file+extension) | |
os.rename(path, new_file) | |
def clean_folder(name, path): | |
clean_folder = clean(name) | |
base = os.path.dirname(path) | |
new_folder = os.path.join(base, clean_folder) | |
os.rename(path, new_folder) | |
return new_folder | |
def process_folder(path): | |
for f_name in os.listdir(path): | |
if not f_name.startswith("."): | |
f_path = os.path.join(path, f_name) | |
if os.path.isfile(f_path): | |
clean_file(f_name, f_path) | |
if os.path.isdir(f_path): | |
n = clean_folder(f_name, f_path) | |
process_folder(n) | |
process_folder(os.getcwd()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment