-
Notifications
You must be signed in to change notification settings - Fork 1
/
fformat
executable file
·53 lines (41 loc) · 1.42 KB
/
fformat
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/env python3
'''
recursively renames files and folders from the current working dir
to be more linux friendly
by removing special characters, accents and spaces
eg. "rapport télétravail 35.pdf" => "rapport_teletravail_35.pdf"
'''
import os
import re
import 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).rstrip("_")
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, f"{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())