Reputation: 479
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.
Upvotes: 5
Views: 3369
Reputation: 43870
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)
Upvotes: 1
Reputation: 353499
I suspect you're using Python 3. The way you open files for writing csv
s 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.]
Upvotes: 8