Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return index for rows in csv module python

Tags:

python

csv

I'm trying to return a specific string that reads out "RowX: [sum of row]" for each row of a tsv table where X = the row number (index +1). So far I can get everything to work except for the row number.

My code:

#!/usr/bin/env python

from __future__ import division, print_function

import sys
import csv



def my_sum(row):
    a = 0
    for i in row:
    a = a + float(i)
    return a

def main():
    tsvfile_input = sys.argv[1]
    data = csv.reader(open(tsvfile_input), delimiter = '\t')

    for row in data:
        RowSum = my_sum(row)
        print('Row' + 'X' + ': ' + str(RowSum))




if __name__ == '__main__':
    main()

So far in place of 'X' I've tried data.index(), which returned:

AttributeError: '_csv.reader' object has no attribute 'index'

Sorry if obvious. I'm extremely new to coding and am doing this as part of an exercise. Also, if you're wondering why I didn't just use sum(), it's part of the exercise to not use sum().

Thanks!

like image 608
AML Avatar asked Jul 16 '26 14:07

AML


1 Answers

How about enumerating the data?

for index, row in enumerate(data):
    RowSum = my_sum(row)
    print('Row %d: %f' % (index + 1, rowSum))

Python also has sum function already, so you can do:

for index, row in enumerate(data):
    print('Row %d: %f' % (index + 1, sum(float(num) for num in row)))

Edit (full example of the main function):

def main():
    tsvfile_input = sys.argv[1]
    data = csv.reader(open(tsvfile_input), delimiter = '\t')
    for index, row in enumerate(data):
        print('Row %d: %f' % (index + 1, sum(float(num) for num in row)))
like image 115
Reut Sharabani Avatar answered Jul 18 '26 05:07

Reut Sharabani