Question:
Exporting table in Python to csv or Excel?
2013-08-06 15:07:36 UTC
Hello Everyone,

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)

Which gave me exactly what I was looking for, but it's not in the format that I need.

Then I found another set of code to help me to get it into the viewable format that I needed:

import csv
import sys
csv_writer = csv.writer(sys.stdout, delimiter=',')
csv_writer.writerows(table)

This produces:

"True,True,True,True,True,True
True,True,True,True,True,False
True,True,True,True,False,True
True,True,True,True,False,False
True,True,True,False,True,True
True,True,True,False,True,False
True,True,True,False,False,True..." (I'm not going to post the whole list.)

Where I am really stuck at is how to get that list into a csv or excel format.

I tried this after some research:

csv_writer2 = csv.writer(open('C:\\blahblah4.csv','w')… delimiter=',')
for row in table:
csv_writer2.writerow(row)

Unfortunately, all I end up with is a blank csv file that is saying it is open by another program and a bunch of output in my window that looks like:

31
32
32
33
32
33
33
34
32
33
33
34
33
34
34
35
32
33
33
34
33
34
34
35

Could someone please look at my code and let me know where I am going wrong?

I know I have heard about opening and closing files, but this does not seem to work with csv.


Thanks!
Three answers:
2013-08-06 15:53:30 UTC
I already said this in one of you deleted questions. But file input and output is much more simple that what you a trying to do:



file = open("myFile.csv", "w")

file.write( "Hello,World");

file.close()



That's it. Make sure to close your file, otherwise it will not save. For adding rows we would use new line at the end and go through the elements with a loop



for item in myArray:

.... file.write(item+"\n");
2013-08-09 21:31:36 UTC
absolutely true.
2013-08-06 22:34:42 UTC
tldr


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...