Search code examples
python-3.xcsvexport-to-csvpython-itertools

Writing to csv file with itertools.product


I have created a script with unique combinations, but I'm stuck on how to go about writing it into a csv file. Right now it's just printing out in my command line and hard to get a good grasp of the data.

My code:

from itertools import combinations, product

crust = ['Thin Crust', 'Hand Tossed']
topping = ['Bacon', 'Pepperoni', 'Steak']
sauce = ['Tomato', 'BBQ', 'Ranch']

topping_combs = combinations(topping, r=2)
sauce_combs = combinations(sauce, r=2)

topping_combs = list(topping_combs)
sauce_combs = list(sauce_combs)

prod = product(crust, topping_combs, sauce_combs)
for c, t, s in prod:
    print(c, *t, *s, sep=', ')

Solution

  • Here is the code. It will open the csv file and write it with each iteration of the for loop. You will see one item in each cell as it was given in the terminal.

    from itertools import combinations, product
    import csv
    crust = ['Thin Crust', 'Hand Tossed']
    topping = ['Bacon', 'Pepperoni', 'Steak']
    sauce = ['Tomato', 'BBQ', 'Ranch']
    
    topping_combs = combinations(topping, r=2)
    sauce_combs = combinations(sauce, r=2)
    
    topping_combs = list(topping_combs)
    sauce_combs = list(sauce_combs)
    
    prod = product(crust, topping_combs, sauce_combs)
    combine_list=[]
    with open('Book1.csv', 'w', newline='') as file:
        for c, t, s in prod:
            print(c, *t, *s, sep=', ')
    
            writer = csv.writer(file)
            writer.writerow([c,*t,*s])