[Tutor] renumbering a sequence

Paul McGuire ptmcg at austin.rr.com
Wed Aug 27 15:24:39 CEST 2008


I am thinking along similar lines as Simone, but I suspect there is still a
missing step.  I think you need to know what the mapping is from old name to
new name, so that you can do something like rename or copy the files that
these names represent.

Python's built-in zip() method does the trick here (zip comes in handy in so
many ways, it is a good tool to add to your at-hand Python skill set).
Don't think of "zip" as in the common file compression scheme.  In Python,
zip() acts like a zipper, matching together the entries from 2 or more lists
the way a zipper matches the teeth from its two sides.  For instance, here
is a simple example of zip() from the command line:

>>> print zip("ABC","123")
[('A', '1'), ('B', '2'), ('C', '3')]

You can imagine how easy it would be to make a dict with zip:

>>> print dict(zip("ABC","123"))
{'A': '1', 'C': '3', 'B': '2'}


For your problem, here is how to zip your old and new file lists together,
and a hypothetical use of such a mapping (to rename the original files):

import os
original_list = sorted(unordered_list)

# use a list comprehension to construct list of new file names in order
new_list = [ "frame.%04d.dpx" % i for i in xrange(len(original_list)) ]

# map old names to new names - zip creates a list of tuples
# using an item from each list in order
file_mapping = zip(original_list, new_list)

# rename files to consecutive order
for oldname,newname in file_mapping:
    if oldname != newname:
        os.rename(oldname,newname)

-- Paul



More information about the Tutor mailing list