Skip to content

Instantly share code, notes, and snippets.

@JamesAwesome
Created May 23, 2014 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamesAwesome/160a8ec9aade077b7314 to your computer and use it in GitHub Desktop.
Save JamesAwesome/160a8ec9aade077b7314 to your computer and use it in GitHub Desktop.
normalize file names recursively
#!/usr/bin/python3 -tt
import sys, os
def normalize(s):
subs = [ ('. ', '.' ), (' - ','-'), (', ',','), (' + ', '+'),
(' & ', '+'), (' ','_'), ('[',''), (']',''),
('(',''), (')',''), ("'",""), ('"',''),
('#','no'), ('!', ''), ('*', '') ]
for a, b in subs:
s = s.replace(a, b)
return s
def main():
if len(sys.argv) >= 2:
baseDir = sys.argv[1]
else:
baseDir = os.getcwd()
for root, subDirs, files in os.walk(baseDir, topdown=False):
# Move files before directories, else we would have to os.walk twice
for f in files:
# It's important to not normalize the root directory
f_path = os.path.join(root, f)
n_path = os.path.join(root, normalize(f))
if f_path != n_path:
print(f_path + " => " + n_path)
os.rename(f_path, n_path)
# Move directories
for d in subDirs:
# It's important to not normalize the root directory
d_path = os.path.join(root, d)
n_path = os.path.join(root, normalize(d))
if d_path != n_path:
print(d_path + " => " + n_path)
os.rename(d_path, n_path)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment