removing spaces from front and end of filenames

Bengt Richter bokr at oz.net
Mon Jul 14 02:38:56 CEST 2003


On 13 Jul 2003 09:43:46 -0700, hokiegal99 at hotmail.com (hokiegal99) wrote:

>Ha!!
>
>Fixed it with this bit of code:
>
>for root, dirs, files in os.walk('/home/BradTill/python'):
>    for file in files:
>        fname = (file)
>        fname = fname.strip( )
>	newfile = fname
>	if newfile:
     for fname in files:
         newfile = fname.strip()
         if newfile!=fname:  
>	    newpath = os.path.join(root,newfile)
>            oldpath = os.path.join(root,file)
>            os.rename(oldpath,newpath)
>	    print oldpath
>	    print newpath
>
I'd suggest using four spaces instead of tabs ;-)

Why not do the whole thing in one loop? (Ignore my prev post suggestion for final
renaming loop just for spaces):

#XXX# untested !!
import re, os
percent2f_n_bad = re.compile(r'%2f|[*?<>/|\\]') # look for bad chars too
for root, dirs, files in os.walk('/home/rbt/scripts'):
     for fname in files:  
          newfile = percent2f_n_bad.sub('-', fname)
          newfile.strip() # and the space thing
          if newfile != fname: # you really only need to know if something changed, right?
              newpath = os.path.join(root,newfile)
              oldpath = os.path.join(root,fname)
              os.rename(oldpath,newpath)
              print `oldpath` # backticks to get quoted repr, to see spaces
              print `newpath`

Or am I missing something?

Regards,
Bengt Richter




More information about the Python-list mailing list