-
Notifications
You must be signed in to change notification settings - Fork 0
/
clean_names
executable file
·47 lines (38 loc) · 1.37 KB
/
clean_names
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
#!/usr/bin/env python
import sys
import os
import re
import glob
def clean_name(name):
# return "".join([c for c in name if re.match(r'\w', c)])
return re.sub(r"[^a-zA-Z0-9._]+", "_", name).lower()
def iter_filenames(maybe_globs):
# after http://stackoverflow.com/questions/9677312/list-of-files-which-might-contain-wildcards-as-arguments-of-a-python-script
for maybe_glob in maybe_globs:
for filename in glob.iglob(maybe_glob):
yield filename
def append_seqno(name, number):
filename, extension = os.path.splitext(name)
return "".join(filename, "_", str(number), extension)
def rename_file(old_name, new_name):
os.rename(old_name, new_name)
def safe_rename(old_name, new_name):
if old_name == new_name:
return
name = new_name
for idx in xrange(10000 + 1):
if not os.path.exists(name):
rename_file(old_name, name)
return
name = append_seqno(new_name, idx)
raise Exception("index over limit, file {} not renamed".format(old_name))
def main():
for filename in iter_filenames(sys.argv[1:]):
clean = clean_name(filename)
if filename == clean:
print "Filename {} OK. Skipping.".format(filename)
else:
print "Renaming {} to {}.".format(filename, clean)
safe_rename(filename, clean)
if __name__ == "__main__":
main()