Python csv.DictReader - how to reverse output?
Question: I'm trying to reverse the way a file is read. I am using DictReader because I
want the contents in a Dictionary. I'd like to read the first line in the file
and use that for the Keys, then parse the file in reverse (bottom to top) kind
of like the linux "tac" command. Is there an easy way to do this? Below is my
code to read the file into a dictionary and write it to a file...

    
    
    reader = csv.DictReader(open(file_to_parse, 'r'), delimiter=',', quotechar='"')
    for line in reader:
        # ...
    

This code works to process the file normally, however.. I need it to read the
file from the end.

In other words, I'd like it to read the file:

    
    
    fruit, vegetables, cars
    orange, carrot, ford
    apple, celery, chevy
    grape, corn, chrysler
    

and be able to have it return:

    
    
    {' cars': ' chrysler', ' vegetables': ' corn', 'fruit': 'grape'}
    {' cars': ' chevy', ' vegetables': ' celery', 'fruit': 'apple'}
    {' cars': ' ford', ' vegetables': ' carrot', 'fruit': 'orange'}
    

instead of:

    
    
    {' cars': ' ford', ' vegetables': ' carrot', 'fruit': 'orange'}
    {' cars': ' chevy', ' vegetables': ' celery', 'fruit': 'apple'}
    {' cars': ' chrysler', ' vegetables': ' corn', 'fruit': 'grape'}
    


Answer: You'll have to read the _whole_ CSV file into memory; you can do so by calling
`list()` on the reader object:

    
    
    with open(file_to_parse, 'rb') as inf:
        reader = csv.DictReader(inf, skipinitialspace=True)
        rows = list(reader)
    
    for row in reversed(rows):
    

Note that I used the file as a context manager here to ensure that the file is
closed. You also want to open the file in binary mode (leave newline handling
to the `csv` module). The rest of the configuration you passed to the
`DictReader()` are the defaults, so I omitted them.

I set `skipinitialspace` to True, as judging from your sample input and output
you do have spaces after your delimiters; the option removes these.

The `csv.DictReader()` object takes care of reading that first line as the
keys.

Demo:

    
    
    >>> import csv
    >>> sample = '''\
    ... fruit, vegetables, cars
    ... orange, carrot, ford
    ... apple, celery, chevy
    ... grape, corn, chrysler
    ... '''.splitlines()
    >>> reader = csv.DictReader(sample, skipinitialspace=True)
    >>> rows = list(reader)
    >>> for row in reversed(rows):
    ...     print row
    ... 
    {'cars': 'chrysler', 'vegetables': 'corn', 'fruit': 'grape'}
    {'cars': 'chevy', 'vegetables': 'celery', 'fruit': 'apple'}
    {'cars': 'ford', 'vegetables': 'carrot', 'fruit': 'orange'}
    

