getting values from a text file (newby)

Steve Holden steve at holdenweb.com
Sun Feb 1 14:19:55 EST 2009


Stephen Hansen wrote:
> 
> 
> On Sun, Feb 1, 2009 at 9:24 AM, vsoler <vicente.soler at gmail.com> wrote:
> 
>     Hi,
> 
>     My foo.txt file contains the following:
> 
>     1,"house","2,5"
>     2,"table","6,7"
>     3,"chair","-4,5"
> 
>     ... as seen with notepad.
> 
>     This file was created with the OpenOffice Calc spreadsheet, but since
>     I use comma as the decimal separator for numbers, the last value in
>     each line appears sorrounded by quotes.
> 
>     I would like to obtain:
> 
>     [[1,"house",2.5], [2,"table",6.7], [3,"chair",-4.5]]
> 
> 
> If I read your requirements, right, I think you want:
> 
> import csv
> 
> data = []
> 
> reader = csv.reader(open("filename", "r"))
> for line in reader:
>      data.append(
>          line[0], line[1], float(line[2].replace(",", "."))
>      )
> 
> print data
> 
> Although you may want to replace that last bit with
>     decimal.Decimal(line[2].replace(",","."))
> 
> If you want an exact result and not the approximate floating point result.
> 
> Basically the csv module can read through the CSV file very easily, but
> because you're using commas instead of points you just have to edit that
> out before you convert it to a number.
> 
alternatively look at locale.atof() to convert according to what I
presume are the conventions of your locale ...

regards
 Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list