[Tutor] renaming files within a directory
davidwilson at Safe-mail.net
davidwilson at Safe-mail.net
Sun Jul 26 21:34:09 CEST 2009
OK I am lost ;(
I changed the code to:
>>> reader = csv.reader(open("countries.csv"), delimiter=";")
>>> for row in reader:
... print row
...
['bi', 'Burundi']
['km', 'Comoros']
['dj', 'Djibouti']
['er', 'Eritrea']
...
Now each row is a list with two items each.
But when I do this:
>>> dic = []
>>> for row in reader:
... newdic.append({row[0]: row[1]})
...
>>> dic
[]
I get an empty dictionary
-------- Original Message --------
From: Tim Golden <mail at timgolden.me.uk>
Apparently from: tutor-bounces+davidwilson=safe-mail.net at python.org
To:
Cc: tutor at python.org
Subject: Re: [Tutor] renaming files within a directory
Date: Sun, 26 Jul 2009 18:32:43 +0100
> 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?
>
> TJG
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list