Reputation: 135
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?
Upvotes: 3
Views: 207
Reputation: 692
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
Upvotes: 1
Reputation: 113915
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
Upvotes: -1
Reputation: 25374
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)
Upvotes: 3