Question

I have a text file where I want to write values from following three lists:

a = [1,2,3]
b = [4,3,2]
c = [7,8,9]

in format:

a-b
c

so the arrangement in text file would look like:

1-4   2-3   3-2  
7     8     9

I have tried following

for x,y,z in zip(a,b,c): ofile.write("p%s-%s\n%s\t" %(x,y,z))

But output in text file is arranged like this:

1-4
7     2-3
8     3-2
9

Any suggestions on how to return to first line and arrange text as needed would be appreciative.

Was it helpful?

Solution

Zip a and b on their own, write that line, then write c on the next:

ofile.write('\t'.join(['{}-{}'.format(*pair) for pair in zip(a, b)]) + '\n')
ofile.write('\t'.join(map(str, c)) + '\n')

This uses str.join() to put tabs between the values on a line.

It'd be easier to use the csv module to take care of turning values into strings and to write tabs and line separators:

writer = csv.writer(ofile, delimiter='\t')
writer.writerow(['{}-{}'.format(*pair) for pair in zip(a b)])
writer.writerow(c)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top