Liam
Liam

Reputation: 63

Python: Help with new line character

I read in a text file that is tab delimited, i then have a list for each line, i then index out the first entry of each list, i then write this to a file. code below:

import csv
z = csv.reader(open('output.blast'), delimiter='\t')
k = open('output.fasta', 'w')
for row in z:
    print row[1:12]
    for i in row[1:12]:
        k.write(i+'\t')

When writing to the file it writes it as one long line, i would like a new line to be started after the 11th (last) entry in each list. But i cannot figure out where to put the new line charater

Upvotes: 4

Views: 7101

Answers (3)

job
job

Reputation: 9273

If you're writing it back out to a tab separated format why not use the csv package again?

r = csv.reader(open('output.blast'),delimiter='\t')
outfile = open('output.fasta','w')
w = csv.writer(outfile,delimiter='\t')
w.writerows(row[1:12] for row in r)
outfile.flush()
outfile.close()

Upvotes: 2

A. Levy
A. Levy

Reputation: 30626

import csv
z = csv.reader(open('output.blast'), delimiter='\t')
k = open('output.fasta', 'w')
for row in z:
    print row[1:12]
    for i in row[1:12]:
        k.write(i+'\t')
    k.write('\n ') # <- write out the newline here.

Upvotes: 0

Michael Mrozek
Michael Mrozek

Reputation: 175695

It sounds like you just want it after each row, so put it at the end of the for loop that iterates over the rows:

for row in z:
    print row[1:12]
    for i in row[1:12]:
        k.write(i+'\t')
    k.write('\n')

Upvotes: 6

Related Questions