removing spaces from front and end of filenames

hokiegal99 hokiegal99 at hotmail.com
Sun Jul 13 03:42:56 CEST 2003


This script works as I expect, except for the last section. I want the 
last section to actually remove all spaces from the front and/or end of 
filenames. For example, a file that was named "  test  " would be 
renamed "test" (the 2 spaces before and after the filename removed). Any 
suggestions on how to do this?

import os, re, string
print " "
print "--- Remove '%2f' From Filenames ---"
print " "
percent2f = re.compile('%2f') #look for this exact string.
for root, dirs, files in os.walk('/home/rbt/scripts'):
     for file in files:
         badchars = percent2f.findall(file)
         newfile = ''
         for badchar in badchars:
             newfile = file.replace(badchar,'-') #replace %2f with a -
         if newfile:
             newpath = os.path.join(root,newfile)
             oldpath = os.path.join(root,file)
             os.rename(oldpath,newpath)
	    print oldpath
	    print newpath
print " "
print "--- Done ---"
print " "
print "--- Remove Bad Characters From Filenames ---"
print " "
badcharset = re.compile(r'[*?<>/\|\\]') #remove any occurance of *?<>/|\
for root, dirs, files in os.walk('/home/rbt/scripts/'):
     for file in files:
         badchars = badcharset.findall(file)
         newfile = ''
         for badchar in badchars:
             newfile = file.replace(badchar,'-') #replace with a dash.
         if newfile:
             newpath = os.path.join(root,newfile)
             oldpath = os.path.join(root,file)
             os.rename(oldpath,newpath)
	    print oldpath
	    print newpath
print " "
print "--- Done ---"
print " "
print "--- Remove Spaces From Filenames ---"
print " "
for root, dirs, files in os.walk('/home/rbt/scripts'):
     for file in files:
         fname = (file)
         fname = fname.strip( )
	print fname
print " "
print "--- Done ---"
print " "





More information about the Python-list mailing list