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’]
If
listais[['apple','car','red'],['orange','boat','black']], then eachkin 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:Edit based on comments: If
listais['apple, 'car', 'red', 'orange', 'boat', 'black']and you want 3 elements per line, you can just change thefortarget to a list comprehension that returns the appropriate sub-lists:There are other ways to break a list into chunks; see this SO question