more regexp

hokiegal99 hokiegal99 at hotmail.com
Fri Jul 11 02:52:07 CEST 2003


I can replace all spaces in filenames and directory names with this bit 
of code: (thanks to all who helped me get this!)

> fspaces = re.compile('[ ]')
> 
> for root, dirs, files in os.walk('/test/dir'): 
> for file in files:
> badchars = fspaces.findall(file) #find spaces
> newfile = ''
> for badchar in badchars:
> newfile = file.replace(badchar,'%')
> if newfile:
> newpath = os.path.join(root,newfile)
> oldpath = os.path.join(root,file)
> os.rename(oldpath,newpath)


> dspaces = re.compile('[ ]')
> 
> for root, dirs, files in os.walk('/test/dir'): 
> for dir in dirs:
> badchars = dspaces.findall(dir) #find spaces
> newdir = ''
> for badchar in badchars:
> newdir = dir.replace(badchar,'%')
> if newdir:
> newpath = os.path.join(root,newdir)
> oldpath = os.path.join(root,dir)
> os.rename(oldpath,newpath)

Now, I'd like to be able to search for the '%' character at the begining 
and the ending of filenames and dirs and remove them entirely. Could 
someone suggest a way to do this? Any tips are welcomed!





More information about the Python-list mailing list