[Tutor] os.path.walk

Jeff Shannon jeff@ccvcorp.com
Mon Feb 24 14:31:01 2003


Bob Gailer wrote:

> import os
> def visit(arg, dirname, names):
>     dirname = dirname + '\\'
>     for name in names:
>         (root, ext) = os.path.splitext(name)
>         if ext and (ext != '.mp3'):
>             os.rename(dirname + name, dirname + root + '.mp3')
> os.path.walk("G:\\Mp3s", visit, None)


Ah, yes, I hadn't thought about how os.path.walk and os.rename would 
need directory names handled.  However, after commenting that 
os.path.splitext() was preferable, you should know better than to 
hard-code directory separators.  ;)  That's what os.path.join() is for.  

Also, the 'if ext' part is unneeded, as an empty string in ext will 
always not equal '.mp3' -- you could use this sort of structure to 
short-circuit a lengthy evaluation of a second clause, but a simple 
comparison of strings is not lengthy.  

def visit(arg, dirname, names):
    for name in names:
        root, ext = os.path.splitext(name)
        if ext != '.mp3':
            os.rename(os.path.join(dirname, name), os.path.join(dirname, 
root+'.mp3'))

Jeff Shannon
Technician/Programmer
Credit International