[Tutor] renaming files within a directory

Alan Gauld alan.gauld at btinternet.com
Mon Jul 27 18:27:45 CEST 2009


<davidwilson at Safe-mail.net> wrote 


> files = set([file for file in glob.glob('Flag_of_*.svg')])
> 
> for file in files:
>    file = file[8:-4]

Yu probably want to keep the filename unouched and 
use a variable like country here.

>    if file.startswith('the_'):
> file = file[4:]
>    if countries.has_key(file):
> b = 'flag-'+ countries[file] + '.svg'
> print b
> rename(file, b)

You are trying to use file in the rename but you have 
modified the filename so it is no longer valid. I'd use 
filename as the variable in the for loop and country 
for the modified version used to access the dictionary.

> $ python rename_svg.py 
> Uganda flag-ug.svg

Where does the Uganda come from? Loooks like the 
real code has an extra print statement somewhere?


HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list