renaming files

Miki Tebeka tebeka at cs.bgu.ac.il
Tue Jan 7 04:38:00 EST 2003


Hello, 

> I'm new to python and trying to learn the language by doing some everyday
> tasks in it.
> I wanted to convert the following simple csh script to python:
> 
> foreach i (test-????.*)
>   mv $i `echo $i | sed 's/test/final/'`
> end
> 
> I can't find no easy way. I don't want to use a system call to 'ls', so got
> a list
> of files with os.listdir(), but how can I get a selective list?
> I can match "test-" with string.find, but I'm really looking for test-????.*
> (csh wildcards).
What you're looking for is the 'glob' library:
--------------
#!/usr/bin/env python
from glob import glob
from os import rename

for file in glob('test-????.*'):
    rename(file, file.replace('test', 'final'))
--------------
Note that globbing regular expressions are differnt from the 're' module ones.

HTH.
Miki




More information about the Python-list mailing list