Skip to content

Instantly share code, notes, and snippets.

@fatso83
Created October 28, 2014 12:25
Show Gist options
  • Save fatso83/e39e2aa008ea6e6480ba to your computer and use it in GitHub Desktop.
Save fatso83/e39e2aa008ea6e6480ba to your computer and use it in GitHub Desktop.
Script to remove spaces from all file and folder names under a certain directory root.
# space_remover.py
#
# Script to remove spaces at the end of folder or file names
# This is a problem when creating a folder on a platform other
# than Windows and sharing that folder with a Windows user
# The Windows user will then not be able to work with files
# within that folder.
# The solution is simply to remove the space at the end of
# the folder name, but this is not possible to do through
# the Windows GUI interface. Normal "CMD" also has problems.
# Thus, this script was born :)
# This script must be run in a unix like environment, such
# as Cygwin, Linux or OS X, as the normal Windows
# environment is not able to enter directories with a space
# at the end
#
# Author: Carl-Erik Kopseng <carlerik@gmail.com>
# Date: 2014-10-28
import sys, os, re
from os.path import isfile, isdir
pattern = re.compile("(.*) $")
def remove_ending_space(name, do_rename=True):
match = pattern.match(name)
if not match: return
new_name = match.group(1)
print "Renaming \"" + name + "\" to \"" + new_name + "\""
if do_rename:
os.rename(name, new_name)
def usage():
print("\nUSAGE: %s [-r] [directory-name]" % (sys.argv[0]))
exit(1)
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-r", "--rename",
action="store_true", dest="rename", default=False,
help="Remove spaces at the end of a file or folder name")
(options, args) = parser.parse_args()
if len(args) == 0:
print("No directory names given. Please supply a directory name to recurse")
usage()
directory = args[0]
if not isdir(directory):
print(directory + " is not a name of a folder name")
usage()
if not options.rename:
print("\nTEST RUN - NOT ACTUALLY RENAMING FILES. Supply \"-r\" to do renaming\n")
# Important to do bottom-up to avoid having to do multiple executions
for dirname, dirs, files in os.walk(directory, topdown=False):
import os.path
for old_name in files+dirs:
remove_ending_space(os.path.join(dirname, old_name), options.rename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment