Reputation: 48976
I'm trying to find the average of each row in a CSV file as follows:
import csv
with open('file.csv') as handle:
reader = csv.reader(handle, quoting=csv.QUOTE_NONNUMERIC)
for row in reader:
scores = row
average = sum([float(score) for score in scores]) / len(scores)
However, I'm always getting the following error:
ValueError: could not convert string to float:
'0.3183098861837984\t0.0021994616367169914\t0.0017398716418448568\t0.002779444153298143\t0.0044629274068791434\t0.0012644430669709003\t0.003083531279794444\t0.004509550881264837\t0.003608705125189259\t0.006833702582258458\t0.0018230394455706783\t0.001852023514636493\t0.004720184835956941\t0.006038977572546727\t0.004769535833937563\t0.0016622734203053761\t0.009311664834557762\t0.002327769746299017\t0.0020053588662354263\t0.006252191840044608\t0.006794853486350821\t0.007258945010249113\t0.00559368878955651\t0.002391455287537788\t0.002168369276873031'
How can I fix this error?
Upvotes: 2
Views: 17805
Reputation: 3519
.csv
file is tab
separated and not ,
separated delimiter='\t'
while reading the csv file. This should fix the problem.import csv
with open('file.csv') as handle:
reader = csv.reader(handle, delimiter='\t', quoting=csv.QUOTE_NONNUMERIC)
for row in reader:
scores = row
average = sum([float(score) for score in scores]) / len(scores)
Upvotes: 2