Writing output csv file python
Question: I'm trying to write a list into a csv file so that it's properly formatted.
I've read from other stack overflow posts that below is the correct way to do
so, (in order to preserve commas that I want to be printed out, etc), but this
is just not working for me.

Rather than printing every list (within `final_list`) in its own csv row, it
just prints one list per cell in one long, continuous line aka no line breaks.
Any ideas on what I can do?

    
    
    import csv 
    
    final_list = ['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']
    
    for key, value in sorted(stats_dict.iteritems()):
        if value[5] != 0:
            final_list.append([key, value[4], value[5], value[0], value[1]])
    
    with open("output.csv", "wb") as f:
        writer = csv.writer(f)
        writer.writerow(final_list)
    


Answer: You need to split your data into headers and then the rows (of data).

    
    
    header = ['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']
    
    final_list = []
    
    for key, value in sorted(stats_dict.iteritems()):
        if value[5] != 0:
            final_list.append([key, value[4], value[5], value[0], value[1]])
    
    with open('output.csv', 'wb') as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerow(header)
        writer.writerows(final_list) # note .writerows
    
    # f.close() - not needed, the with statement closes the file for you
    

