Counting using DictReader
Question: Still new to Python, this is how far I've managed to get:

    
    
    import csv
    import sys
    import os.path
    
    #VARIABLES
    
    
    reader = None
    col_header = None
    total_rows = None
    rows = None
    
    #METHODS
    
    
    def read_csv(csv_file):
    #Read and display CSV file w/ HEADERS
        global reader, col_header, total_rows, rows
    
    #Open assign dictionaries to reader
        with open(csv_file, newline='') as csv_file:
            #restval = blank columns = - /// restkey = extra columns +
            reader = csv.DictReader(csv_file, fieldnames=None, restkey='+', restval='-', delimiter=',',
                                    quotechar='"')
    
            try:
                col_header = reader.fieldnames
                print('The headers: ' + str(reader.fieldnames))
                for row in reader:
                    print(row)
    
                #Calculate number of rows
                rows = list(reader)
                total_rows = len(rows)
            except csv.Error as e:
                sys.exit('file {}, line {}: {}'.format(csv_file, reader.line_num, e))
    
    
    def calc_total_rows():
        print('\nTotal number of rows: ' + str(total_rows))
    

My issue is that, when I attempt to count the number of rows, it comes up as 0
(impossible because csv_file contains 4 rows and they print on screen. I've
placed the '#Calculate number of rows' code above my print row loop and it
works, however the rows then don't print. It's as if each task is stealing the
dictionary from one another? How do I solve this?


Answer: The problem is that the `reader` object behaves like a file as its iterating
through the CSV. Firstly you iterate through in the `for` loop, and print each
row. Then you try to create a list from whats left - which is now empty as
you've iterated through the whole file. The length of this empty list is 0.

Try this instead:

    
    
    rows = list(reader)
    for row in rows:
        print(row)
    
    total_rows = len(rows)
    

