[Tutor] os.path.walk

Jeff Shannon jeff@ccvcorp.com
Sat Feb 22 01:37:16 2003


Gus Tabares wrote:

>Traceback (most recent call last):
>  File "mp3.py", line 19, in ?
>    os.path.walk("G:\\Mp3s", visit, dummy)
>  File "C:\Python22\lib\ntpath.py", line 318, in walk
>    func(arg, top, names)
>  File "mp3.py", line 12, in visit
>    os.rename(names, (names[:-4] + '.mp3'))
>OSError: [Errno 2] No such file or directory
>
>I am 100% positive my G:\Mp3s dir does exist:)
>  
>
Ah, but is that *really* what the error is about?  :)


def visit(arg, dirname, names):
    for names in dirname:
        if (names[-4:] != '.mp3'):
            os.rename(names, (names[:-4] + '.mp3'))
        else:
            pass


Now, in this visit() function, 'dirname' will be the name of the 
directory (in string form), while 'names' will be a list of all the 
filenames within that directory.

However, your first line, 'for names in dirname:', tries to iterate over 
the string that's bound to dirname, i.e. "G:\Mp3s".  Iterating over a 
string yields a single character, so 'names' gets re-bound to the letter 
'G'.  Obviously you're going to have problems with renaming the file 'G' 
...  :)

As a minor additional point, it's good form to use the os.path module to 
handle your filenames, and the 'else: pass' bit is superfluous, as is 
the use of a 'dummy' list (just use None instead).

Try this instead:

def visit(arg, dirname, names):
    for name in names:
        base, ext = os.path.splitext()
        if ext != '.mp3':
            newname = '%s.mp3' % base
            os.rename(name, newname)

os.path.walk("G:\\Mp3s", visit, None)

Feel free to ask for further clarifications about the reasoning behind this (but also be prepared to wait until Monday for an answer, since I don't check this email address on weekends :) )

Jeff Shannon
Technician/Programmer
Credit International