Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding csv DictWriter syntax in python

Tags:

python

csv

I was looking at the very helpful answer to a previous SO question which can be found here when attempting to write a list of dicts to a CSV file. The code I used was:

with open((filename), 'wb') as outfile:
    write = csv.DictWriter(outfile, keyList)
    write.writer.writerow(keyList)
    write.writerows(data)

where keyList is a list of headers for the csv file.

The code worked great, which is nice, but I don't understand why I had to explictly call the underlying writer instance to write the keyList (the headers). I tried that line as write.writerow(keyList) and it didn't work. I'm curious why that is so I can better understand how Python's DictWriter works.

Is there a cleaner/nicer way of writing this?

like image 454
user139014 Avatar asked Jul 01 '13 06:07

user139014


People also ask

What is csv DictWriter in python?

Python CSV DictWriter The csv. DictWriter class operates like a regular writer but maps Python dictionaries into CSV rows. The fieldnames parameter is a sequence of keys that identify the order in which values in the dictionary passed to the writerow method are written to the CSV file.

What Is syntax for read CSV file in python?

Using the CSV LibraryThe open() method takes two arguments of type string . First the file name, and second a mode argument. We are using r for read, however this can be omitted as r is assumed by default. We then iterate over all the rows.

What is the difference between Writerow () and Writerows () in the csv module?

The technical difference is that writerow is going to write a list of values into a single row whereas writerows is going to write multiple rows from a buffer that contains one or more lists.

How do you read a CSV file and encoding in python?

encode('utf-8') filename = 'output. csv' reader = unicode_csv_reader(open(filename)) try: products = [] for field1, field2, field3 in reader: ...


1 Answers

You appear to be relying on undocumented behavior. A DictWriter object doesn't have an "official" writer method.

The correct way to output the CSV headers is to call

write.writeheader()
like image 140
Tim Pietzcker Avatar answered Nov 06 '22 12:11

Tim Pietzcker