more regexp

H

hokiegal99

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!
 
J

John Hunter

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

Sorry if I'm missing something since I'm jumping into this thread
late, but if all you want to do is replace spaces, why do you need
regexps? Can't you just use string.replace?

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

See also lstrip and rstrip to remove chars (default whitespace) from
the beginning or end of a string (strip does both beginning and end).

JDH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top