[Tutor] renaming files within a directory

Tim Golden mail at timgolden.me.uk
Sun Jul 26 19:32:43 CEST 2009

davidwilson at Safe-mail.net wrote:
> Here is what I have so far, but I get stuck on the mapping of the filename with the csv file.
>>>> import os
>>>> files = [file for file in os.listdir(os.getcwd()) if file.endswith('svg')]
>>>> files
> ['Flag_of_Abkhazia.svg', 'Flag_of_Afghanistan.svg', 'Flag_of_Albania.svg', 'Flag_of_Algeria.svg', 'Flag_of_Andorra.svg', 'Flag_of_Angola.svg', 'Flag_of_Antigua_and_Barbuda.svg', 'Flag_of_Argentina.svg', 'Flag_of_Armenia.svg', 'Flag_of_Australia.svg']
>>>> import csv
>>>> reader = csv.reader(open("country.csv"))
>>>> for row in reader:
> ...     print row   
> ['"km";"Comoros"']
> ['"dj";"Djibouti"']
> ['"er";"Eritrea"']
> ['"et";"Ethiopia"']
> ....
> Here is where I am at.
> Not sure how to map the two.

OK. Good stuff so far. You may not actually need
that auxiliary list of files, but no problem really.

Are you familiar with a dictionary in Python? It maps
a key to a value. Here, you want the long names to
be the keys and the short names to be values. If you
were putting them together by hand (as a constant)
it would look something like this:

countries = {
  "Comoros" : "km",
  "Ethiopia" : "et",

and you could look up like this:

ethiopia_tld = countries['Ethiopia']

So what you have to do is to use one of the dictionary
constructors (hint: help (dict)) to create a dictionary
out of the list of lists which you csv reader produced.
You'll need to swap the elements round as the csv has
the code first, but you want the country first.

Does that take you any further forward?


More information about the Tutor mailing list