Praveen Raj Kumar
Praveen Raj Kumar

Reputation: 208

unable to enter for loop in python

Here is my data.csv

a,1,1-Jan-2017
a,2,3-Jan-2017
a,4,14-Feb-2017
b,21,1-Dec-2016
b,7,28-Nov-2016

My target is to print below as final list. Format is unique(first_column),no.of occurences

a,3
b,2 

Written below python script but unable to enter second block to print 'second block' although the same logic works fine in previous loop.

import csv

with open('/home/user/python/data.csv') as csvfile :
    DataCaptured = csv.reader(csvfile,delimiter=',')
    UniqueValues = []
    FinalList = []

    for row in DataCaptured :
            if row[0] not in UniqueValues :
                    UniqueValues.append(row[0])

    print 'Unique values are:\n' + str(UniqueValues)

    for unique in UniqueValues :
            counter = 0
            print 'First block',unique
            for row in DataCaptured :
                    print 'Second block'
                    if unique == row[0] :
                            counter = int(counter)+1
            FinalList.append(unique+','+str(counter))

    print 'Final list:\n' + str(FinalList)

Upvotes: 0

Views: 71

Answers (2)

Scovetta
Scovetta

Reputation: 3152

You could simplify the program above a bit and only iterate through the file once:

import csv

with open('/home/user/python/data.csv') as csvfile :
    unique_values = {}

    for row in csv.reader(csvfile, delimiter=','):
        element = row[0]
        if element not in unique_values:
            unique_values[element] = 0

        unique_values[element] += 1

    for unique, count in unique_values.items():
        print('{0},{1}'.format(unique, count))

Upvotes: 1

PrestonH
PrestonH

Reputation: 566

It's because you've already read over the entire file after the first loop; there are no more rows in the reader's iterator at this point. Use csvfile.seek(0) after the first for loop to return to the beginning of the file, and it will work.

Upvotes: 4

Related Questions