aaaa
aaaa

Reputation: 35

how to write to csv in python?

I have a row:

row = {'A':'valueA', 'B':'valueB', 'C':'valueC'}

Basically I want to open a new csv file and write each value in its column, e.g.

 ---------------------------
|   A     |  B     |   C    |
 ---------------------------
|  ValueA | ValueB | ValueC |
 ---------------------------

I am doing this:

def OandWtonew(filename, row):
with open('Ouput1.csv', 'wt') as csvfile:
    fileout = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    fileout.writerow(row)

but the output I am getting is:

 --------------------------------------------
|   A           |  B           |  C          |
 --------------------------------------------
|  'A':'valueA' | 'B':'valueB' | 'C':'valueC'|
 --------------------------------------------

All replies are much appreciated :)

Upvotes: 2

Views: 4256

Answers (3)

Since the data is a dictionary, csv.DictWriter() may be the most straightforward way to do it. Just make sure the list of header values are in the original order, in this case sorted() may be the easiest:

with open('Ouput1.csv', 'wt') as csvfile:
    fieldnames = sorted(row.keys())  # needs to be the first line in correct order
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow(row)             # writes corresponding value for key in header

CSV view in Excel

Upvotes: 3

hunny_o
hunny_o

Reputation: 43

You can use pandas.DataFrame.to_csv() to easily write to a csv:

import pandas as pd

row = {'A':'valueA', 'B':'valueB', 'C':'valueC'}

#Convert dictionary to a pandas dataframe
df = pd.DataFrame().append(row, ignore_index=True)

# check output
df
    A       B       C
0   valueA  valueB  valueC

# Save to a csv file
df.to_csv('Ouput1.csv',index=False)

Upvotes: 2

J. Blackadar
J. Blackadar

Reputation: 1961

row is of type dict. From the documentation:

import csv
with open('names.csv', 'w') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})

Upvotes: 1

Related Questions