[Tutor] os.path.walk

Bob Gailer ramrom@earthling.net
Fri Feb 21 22:28:08 2003


--=======3009658E=======
Content-Type: text/plain; x-avg-checked=avg-ok-3F2219CD; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 08:28 PM 2/21/2003 -0800, Gus Tabares wrote:
>1 import os
>2 def visit(arg, dirname, names):
>3     for names in dirname:
>4         if (names[-4:] != '.mp3'):
>5             os.rename(names, (names[:-4] + '.mp3'))
>6         else:
>7             pass
>8 dummy = []
>9 os.path.walk("G:\\Mp3s", visit, dummy)

3 - the argument 'names' contains the file names, not 'dirname'
4 - this assumes that the original extension is 3 chars. Not a good idea in 
general. Use os.path.splitext()
5 - you must specify the complete path name, not just the filename
6,7 unnecessary
8,9 can pass None instead of creating a variable

Many minor changes - Try this revision and see if you can understand why 
the changes. One of my assumptions is that there could be subdirectories, 
which would be the reason to use walk instead of glob.

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)


Bob Gailer
mailto:ramrom@earthling.net
303 442 2625

--=======3009658E=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-3F2219CD
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003

--=======3009658E=======--