help: output arrays into file as column

Simon Forman rogue_pedro at yahoo.com
Thu Jul 27 14:18:12 EDT 2006


bei wrote:
> Hi,
>
> I am trying to write several arrays into one file, with one arrays in
> one column. Each array (column) is seperated by space.
> ie. a=[1,2,3, 4] b=[5,6,7,8] c=[9,10,11,12]
> 1  5  9
> 2  6  10
> 3  7  11
> 4  8  12
>
> Now I use the function file.writelines(a), file.writelines(b),
> file.writelines(c). And the output is a sequence of strings without
> newlines between a, b ,c . Also each array stays in row other than
> column.
>
> I am a new comer to python.Any idea about this is appreciated!
>
> Bei

Hi Bei,

file.writelines() works with lists of strings, not lists of numbers, so
I'm going to assume that a, b, and c are already lists of strings..

You can use the zip() function to change the lists in the way you want
to:

|>> a=['1','2','3','4']; b=['5','6','7','8']; c=['9','10','11','12']
|>> zip(a, b, c)
[('1', '5', '9'), ('2', '6', '10'), ('3', '7', '11'), ('4', '8', '12')]

now that you have the data for each line, you can combine them with the
string join() method:

|>> data = zip(a, b, c)
|>> for datum in data:
...     print ' '.join(datum)
...
1 5 9
2 6 10
3 7 11
4 8 12

You can print to an open file object, so the above loop will do what
you need:

|>> f = open('output.txt', 'w')
|>> for datum in data:
...     print >> f, ' '.join(datum)
...
|>> f.close()
|>> print open('output.txt').read()
1 5 9
2 6 10
3 7 11
4 8 12


I hope that helps!

Peace,
~Simon




More information about the Python-list mailing list