First practical Python code, comments appreciated

Kent Johnson kent at kentsjohnson.com
Wed Dec 14 11:05:19 EST 2005


planetthoughtful wrote:
> Hi All,
> 
> I've written my first piece of practical Python code (included below),
> and would appreciate some comments. My situation was that I had a
> directory with a number of subdirectories that contained one or more
> zip files in each. Many of the zipfiles had the same filename (which is
> why they had previously been stored in separate directories). I wanted
> to bring all of the zip files (several hundrd in total) down to the
> common parent directory and obviously rename them in the process by
> appending a unique string to each filename.
> 
> The code below did the job admirably, but I don't imagine it is
> anywhere near as efficiently written as it could and should be. Note:
> I'm aware there was no need, for example, to wrap the "os.walk(path)"
> statement in a def -- in a couple of places I added extra steps just to
> help familiarize myself with Python syntax.
> 
> I'd very much like to see how experienced Python coders would have
> achieved the same task, if any of you can spare a couple of minutes to
> share some knowledge with me.
> 
> Many thanks and much warmth,
> 
> planetthoughtful
> 
> import os
> fcount = 0
> path = 'X:\zipfiles'
> def listFiles(path):
>     mylist = os.walk(path)
>     return mylist

Note that os.walk() doesn't return a list, it returns an iterable object (a generator). 
Your usage will work for either, but your names are misnomers.
> 
> filelist = listFiles(path)
> for s in filelist:

I would write
for dirpath, dirnames, filenames in filelist:

which gives names to what you call s[0] and s[2]

or just
for dirpath, dirnames, filenames in os.walk(path):

Kent

>     if len(s[2]) > 0:
>         for f in s[2]:
>             pad = str(fcount)
>             if len(pad) == 1:
>                 pad = "00" + pad
>             elif len(pad) == 2:
>                 pad = "0" + pad
> 
>             (fname, fext) = os.path.splitext(f)
>             oldname = f
>             newname = fname + "_" + pad + fext
>             os.rename(s[0] + "\\" + oldname, path + "\\" + newname)
>             fcount = fcount + 1
> 



More information about the Python-list mailing list