Export Python list to csv

So, I'm trying to create a truth table that I can export in csv or excel format. I am new to Python, so please bear with me if my code is horrible.

I started with this as my truth table code 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 leads me to where I need to be with a truth table in csv format. However, when I open the file in excel, blank lines are inserted between my records. I tried the tooltip I found on the Internet where I need to change the input type from w to wb, but I get this error when I do this:

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

I'm not sure where to go from here, because I feel so close to get it in the format I want.

+4
source share
2 answers

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

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

it should work by creating a file that looks like

 False,False,False,False,False,False False,False,False,False,False,True False,False,False,False,True,False [etc.] 
+7
source

And if you do not use 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) 
+1
source

Source: https://habr.com/ru/post/1495664/


All Articles