Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting Python List into csv

Tags:

python

csv

So I am trying to create a truth table that I can export out into either a csv or excel format. I am a newbie to Python, so please bear with me if my code is horrible.

I started with this as my code for the truth table after some research:

import itertools 
table = list(itertools.product([False, True], repeat=6)) 
print(table)

Then I got to this code:

import csv
import sys
with open('C:\\blahblah5.csv','w') as fout:
writer = csv.writer(fout, delimiter = ',')
writer.writerows(table)

This gets me almost to where I need to be with the truth table in a csv format. However, when I open up the file in excel, there are blank rows inserted between my records. I tried a tip I found online where I need to change the input type from w to wb, but I get this error when I do:

Traceback (most recent call last):
File "<pyshell#238>", line 3, in <module>
writer3.writerows(table)
TypeError: 'str' does not support the buffer interface

I am not sure where to go from here because I feel like I am so close to getting this into the format I want.

like image 382
Perdue Avatar asked Aug 07 '13 03:08

Perdue


2 Answers

I suspect you're using Python 3. The way you open files for writing csvs changed a little: if you write

with open("C:\\blahblah5.csv", "w", newline="") as fout:

it should work, producing a file which looks like

False,False,False,False,False,False
False,False,False,False,False,True
False,False,False,False,True,False
[etc.]
like image 88
DSM Avatar answered Oct 16 '22 09:10

DSM


And if not using python3 you should open the file with "wb".

import csv

with open('C:\\blahblah5.csv','wb') as fout:
    writer = csv.writer(fout)
    writer.writerows(table)
like image 23
monkut Avatar answered Oct 16 '22 08:10

monkut