Search code examples
pythondata-manipulation

How to save the results of a for function in an excel file


I need to save all the results from this loop into an excel sheet file:

import itertools


def foo(l):
     yield from itertools.product(*([l] * 18)) 
 

for x in foo('ATCG'):
    print(''.join(x))`

I tried this:

import itertools
import csv


def foo(l):
     yield from itertools.product(*([l] * 18)) 


for x in foo('ATCG'):
    print(''.join(x))
    outfile =  open("primers.csv","w", newline = '')
    writer=csv.writer(outfile)
    writer.writerows(str(foo))   

but it ended up saving only the last result of the loop


Solution

  • Only create the writer once outside the loop or it will overwrite the file completely with each line. Like this:

    import csv
    import itertools
    
    
    def foo(l):
         yield from itertools.product(*([l] * 4))
    
    
    outfile = open("primers.csv","w")
    writer = csv.writer(outfile)
    
    for x in foo('ATCG'):
        row = ''.join(x)
        print(row)
        writer.writerow(row)
       
    

    Note that your loop creates a lot of permutations, it might not end for a very, very long time and the file will be huge:

    AAAAAATGTGTAAGAACT
    AAAAAATGTGTAAGAACC
    AAAAAATGTGTAAGAACG
    AAAAAATGTGTAAGAAGA
    AAAAAATGTGTAAGAAGT