First practical Python code, comments appreciated

planetthoughtful planetthoughtful at
Wed Dec 14 12:54:01 CET 2005

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,


import os
fcount = 0
path = 'X:\zipfiles'
def listFiles(path):
    mylist = os.walk(path)
    return mylist

filelist = listFiles(path)
for s in filelist:
    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