5

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.

2 Answers 2

8

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.]
1
1

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.