ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> python-list
python-list
removing spaces from front and end of filenames
by hokiegal99 other posts by this author
Jul 13 2003 1:42AM messages near this date
Re: HTML Help (CHM) file for Python 2.2.3 | Re: removing spaces from front and end of filenames
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 " "

-- 
http://mail.python.org/mailman/listinfo/python-list
Thread:
hokiegal99
Bengt Richter
Bengt Richter
Bengt Richter
hokiegal99
Stephen Horne
Stephen Horne
Erik Max Francis
hokiegal99
hokiegal99
Jeff Epler
Erik Max Francis

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState Software Inc. All rights reserved