Phil
Phil

Reputation: 377

Python: Simple file formating problem

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']

Upvotes: 0

Views: 95

Answers (2)

Mark Tolonen
Mark Tolonen

Reputation: 178189

It looks like you are processing an input csv file with 22+ columns. Why not just use csv.writer as well to rewrite each line?

A short, working example:

import csv

# generate an input file
f = open('in.csv','w')
f.write('''\
Col1,Col2,Col3,Col4,Col5
1,2,3,4,5
6,7,8,9,10
11,12,13,14,15
''')
f.close()

# open the files (csv likes binary mode)
input = open('in.csv','rb')
output = open('out.csv','wb')

antigens = csv.reader(input)
pad_file = csv.writer(output)

for i in antigens:
    pad_file.writerow([i[4],i[2],i[0]])

input.close()
output.close()

"out.csv" contains:

Col5,Col3,Col1
5,3,1
10,8,6
15,13,11

Upvotes: 0

Michael Mrozek
Michael Mrozek

Reputation: 175705

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

Upvotes: 1

Related Questions