Search code examples
pythoncsvenumerate

How to index rows in my output


My CSV file is as following (two rows with semicolon separated values)

01;John;231;this is row one
02;Paul;745;this is row two

I want result like this:

01  ============== column 1 and row 1
John ============= Column 2 and row 1
231 ============== column 3 and row 1
this is row one ========column 4 and row 1

and so on till the end of csv file.

Till now i am able to fetch column position but not row.

def read_csv(csvfile):
    with open(csvfile, 'rb') as file:
        columns = 4
        reader = csv.reader(file, delimiter=';')
        for row in reader:
            for column in range(0, columns):
                 print row[column], ' ====== ', 'column ', column+1, ' and row ', 

What should i put at the last line of code that i can have row position as well.

Thanks


Solution

  • You can use enumerate:

    def read_csv(csvfile):
        with open(csvfile, 'rb') as file:
            columns = 4
            reader = csv.reader(file, delimiter=';')
            # i will count the rows, starting at 1
            for i, row in enumerate(reader, start=1):
                for column in range(0, columns):
                     print row[column], ' ====== ', 'column ', column+1, ' and row ', i