简体   繁体   中英

Importing CSV file into list python

I've a little problem here. I need to read a txt file and store it into a list, I'm already doing that... but the problem is that I need to manipulate some columns like multiplying then by 30 and so forth so on. (I'm still learning python) (Its python 3.4)

The test.txt file:

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

The 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)

The result is:

['-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?

Python is reading the numbers as strings, so when you do the *3 it thinks "Ah! Matt wants me to put the the string three times in a row!"

If you just convert it to a float first, it'll be fine:

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

You need to parse the columns[3][i] into float like

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

Because

'any_string'*3
>>any_stringany_stringany_string
 100*3
>>300
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM