[Tutor] file name change script

Paul Sidorsky paulsid@shaw.ca
Sun, 24 Mar 2002 19:05:01 -0700


jb wrote:

> Hi, I'm a old fart struggling to learn to program with python and to use
> linux at the same time. I'd be pulling out my hair if only I had some.
> =-)
> 
> What I'm trying to figure out, is how to write a python script which
> would do the following in the bash shell ...
> 
> change all the existing file names in a directory to new file names
> which are made up of sequencial numbers,
> 
> eg.  <oldfilename_x.txt> to <001.txt>
>      <oldfilename_y.txt> to <002.txt>
>      <oldfilename_z.txt> to <003.txt>
>      ...
> 
> Any suggestions would be greatly appreciated

Sure, this is really easy to do.  (Especially since I had a similar
script lying around from a web site restructuring.)  This code will
operate on the present working directory:

import os

count = 1
for fn in os.listdir("."):
    if fn[-4:] == ".txt":
        os.rename(fn, "%03i.txt" % count)
        count = count + 1

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/