Skip to content

Instantly share code, notes, and snippets.

@openp2pdesign
Last active June 30, 2021 04:02
Show Gist options
  • Save openp2pdesign/2c8ac456e83a1e57c6a2 to your computer and use it in GitHub Desktop.
Save openp2pdesign/2c8ac456e83a1e57c6a2 to your computer and use it in GitHub Desktop.
Check and rename files with illegal chars
# -*- encoding: utf-8 -*-
#
# Author: Massimo Menichinelli
# Homepage: http://www.openp2pdesign.org
# License: MIT
#
import string
import os
# Adapted from: http://www.andrew-seaford.co.uk/generate-safe-filenames-using-python/
## Make a file name that only contains safe charaters
# @param inputFilename A filename containing illegal characters
# @return A filename containing only safe characters
def makeSafeFilename(inputFilename):
# Set here the valid chars
safechars = string.letters + string.digits + "~ -_."
try:
return filter(lambda c: c in safechars, inputFilename)
except:
return ""
pass
# Set the path you want to check
path = "/Users/massimo/Documents/FabAcademy2015/europe"
# Check each file in subfolders
for root, dirs, files in os.walk(path):
for name in files:
checkname = makeSafeFilename(name)
if name != checkname:
print "In:",root
print "There was an error with",name
if os.name == "nt":
os.rename(root+"\\"+name, root+"\\"+checkname)
else:
os.rename(root+"/"+name, root+"/"+checkname)
print name,"has been renamed to", checkname
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment