renaming files

Mike C. Fletcher mcfletch at rogers.com
Mon Jan 6 23:50:28 EST 2003


Look at the documentation for the glob module (wildcard-matching is 
called "globbing" in some fields).  Also see the os.rename and 
os.renames functions...

 >>> import glob, os
 >>> for file in glob.glob( r"p:\*.py" ):
...     whatever()

I don't know for sure what you're doing with sed there.  It looks like a 
regex replace of "test" with final, if that's the case, do:

    os.rename( file, file.replace( 'test', 'final', 1) )

That 1 is to signal to replace to only replace the first "test" 
sub-string, so that:

    "test-Greatest-Canadian-Hero.mp3"

won't become:

    "final-Greafinal-Canadian-Hero.mp3"

HTH,
Mike

Hilbert wrote:

>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).
>
>Any suggestions?
>
>Thanks!
>  
>
_______________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://members.rogers.com/mcfletch/








More information about the Python-list mailing list