Importing CSV file into python list

I have a little problem here. I need to read a txt file and store it in a list, I already do that ... but the problem is that I need to manipulate some columns, for example multiply by 30 and so on. (I am still learning python) (its python 3.4)

Test.txt file:

Abacate;Para;PA;-1.1166667;-49.65
Abacate;Amazonas;AM;-3.9463889;-62.9038889

      

Code:

def readFile():
  with open('test.txt') as f:
    reader = csv.reader(f,delimiter=";")
    #reader.next()
    for row in reader:
        for (i,v) in enumerate(row):
            columns[i].append(v)

      

But when I try to use

    for i in range(0,len(columns[3])):
        listTest.append(columns[3][i]*3)

      

Result:

['-1.1166667-1.1166667-1.1166667']
['-1.1166667-1.1166667-1.1166667', '-3.9463889-3.9463889-3.9463889']

      

Expected:

['-3.3500001','-11.8391667']

      

Is there a better way to do this?

+3


source to share


3 answers


Python reads numbers as strings, so when you do *3

, it thinks, "Ah, Matt wants me to put the string three times in a row!"

If you convert it to a float first, everything is fine:



for i in range(0,len(columns[3])):
    listTest.append(float(columns[3][i])*3)

      

+3


source


You need to parse columns[3][i]

to float as

listTest.append(float(columns[3][i])*3)

      



Insofar as

'any_string'*3
>>any_stringany_stringany_string
 100*3
>>300

      

+1


source


import csv
def readFile(infilepath):
    answer = []
    with open(infilepath) as infile:
        for *_head, a, _b in csv.reader(infile, delimiter';'):
            answer.append(float(a) * 3)
    return answer

      

-1


source







All Articles