Skip to content

Instantly share code, notes, and snippets.

@thejoshwolfe
Created May 19, 2012 07:50
Show Gist options
  • Save thejoshwolfe/2729954 to your computer and use it in GitHub Desktop.
Save thejoshwolfe/2729954 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""\
looks for non-utf8, windows-style encodings in filenames and fixes them.
"""
__version__ = "0.0"
import os, sys
def is_utf8(name):
try:
name.decode("utf8")
return True
except UnicodeDecodeError:
return False
color_red = "\x1B[0;31m"
color_green = "\x1B[0;32m"
color_clear = "\x1B[0m"
def red(s):
return color_red + s + color_clear
def green(s):
return color_green + s + color_clear
def deal_with_this(parent, name, options):
path = os.path.join(parent, name)
if is_utf8(name):
return
try:
new_name = name.decode("iso-8859-1").encode("utf8")
except:
sys.stderr.write("WARNING: wtf: " + path + "\n")
return None
if options.verbose:
transform = "{" + red(name) + "," + green(new_name) + "}"
print(os.path.join(parent, transform))
if options.pretend:
return
os.rename(path, os.path.join(parent, new_name))
return new_name
def main(options, args):
for arg in args:
arg = os.path.normpath(arg)
arg_parent, arg_name = os.path.split(arg)
new_name = deal_with_this(arg_parent, arg_name, options)
if new_name:
arg = os.path.join(arg_parent, new_name)
for root, dirs, files in os.walk(arg):
for i in range(len(dirs)):
new_name = deal_with_this(root, dirs[i], options)
if new_name:
dirs[i] = new_name
for name in files:
deal_with_this(root, name, options)
if __name__ == "__main__":
import optparse
parser = optparse.OptionParser(version=__version__, description=__doc__)
parser.add_option("-p", "--pretend", action="store_true", help="don't actually do anything.")
parser.add_option("-v", "--verbose", action="store_true", help="print what's going on. implied by --pretend.")
(options, args) = parser.parse_args()
if args == []:
parser.error("no arguments")
if options.pretend:
options.verbose = True
sys.exit(main(options, args))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment