renaming files

Sean 'Shaleh' Perry shalehperry at attbi.com
Mon Jan 6 23:37:50 EST 2003


On Monday 06 January 2003 19:58, 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!

>>> import os, fnmatch
>>> filter(lambda x: fnmatch.fnmatch(x, '*.cc'), os.listdir('.'))
['Clientmenu.cc', 'Configmenu.cc', 'Iconmenu.cc', 'Rootmenu.cc', 'Screen.cc', 
'Slit.cc', 'Toolbar.cc', 'Window.cc', 'Windowmenu.cc', 'Workspace.cc', 
'Workspacemenu.cc', 'blackbox.cc', 'main.cc']

for those using python 2.x that can also be written as:

>>> [n for n in os.listdir('.') if fnmatch.fnmatch(n, '*.cc')]

See also the glob module.





More information about the Python-list mailing list