Python: Simple file formating problem
Question: I'm using the code below to to write to a file but at the moment it writes
everything onto a new line.

    
    
    import csv
    antigens = csv.reader(open('PAD_n1372.csv'), delimiter=',')
    
    lista = []
    pad_file = open('pad.txt','w')
    
    for i in antigens:
        lista.append(i[16])
        lista.append(i[21])
        lista.append(i[0])
    
    for k in lista:
        pad_file.write(k+',')
        pad_file.write('\n')
    

If say my "lista" looks like

    
    
    [['apple','car','red'],['orange','boat','black']]
    

I would like the output in my text file to be:

    
    
    apple,car,red
    orange,boat,black
    

I know my new line character is in the wrong place but I do now know where to
place it, also how would I remove the comma from the end of each line?

* * *

EDIT

Sorry my "lista" looks like

['apple','car','red','orange','boat','black']


Answer: If `lista` is `[['apple','car','red'],['orange','boat','black']]`, then each
`k` in your loop is going to be one of the sub-lists, so all you need to do is
join the elements of that sub-list on a `,` and output that as a single line:

    
    
    for k in lista:
        pad_file.write(','.join(k))
        pad_file.write('\n')
    

* * *

**Edit** based on comments: If `lista` is `['apple, 'car', 'red', 'orange',
'boat', 'black']` and you want 3 elements per line, you can just change the
`for` target to a list comprehension that returns the appropriate sub-lists:

    
    
    for k in [lista[x:x+3] for x in xrange(0, len(lista), 3)]:
        pad_file.write(','.join(k))
        pad_file.write('\n')
    

There are other ways to break a list into chunks; see [this SO
question](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-
into-evenly-sized-chunks-in-python)

