Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Write two lists into two column text file

Say I have two lists: a=[1,2,3] b=[4,5,6] I want to write them into a text file such that I obtain a two column text file:

1 4
2 5
3 6
like image 871
Arthur Plante Avatar asked Sep 28 '14 07:09

Arthur Plante


People also ask

How do you write two columns in a file in Python?

You can use a different format for each column. E.g. to specify floating point format, with 2 decimal digits and 10 characters wide columns, you would use '%10.2f' .


2 Answers

Simply zip the list, and write them to a csv file with tab as the delimiter:

>>> a=[1,2,3]
>>> b=[4,5,6]
>>> zip(a,b)
[(1, 4), (2, 5), (3, 6)]
>>> import csv
>>> with open('text.csv', 'w') as f:
...    writer = csv.writer(f, delimiter='\t')
...    writer.writerows(zip(a,b))
...
>>> quit()
$ cat text.csv
1       4
2       5
3       6
like image 56
Burhan Khalid Avatar answered Oct 17 '22 18:10

Burhan Khalid


You can use numpy.savetxt(), which is a convenient tool from the numpy library. A minimal example would be as follows:

import numpy as np

xarray = np.array([0, 1, 2, 3, 4, 5])
yarray = np.array([0, 10, 20, 30, 40, 50])
# here is your data, in two numpy arrays

data = np.column_stack([xarray, yarray])
datafile_path = "/your/data/output/directory/datafile.txt"
np.savetxt(datafile_path , data, fmt=['%d','%d'])
# here the ascii file is written. 

The fmt field in np.savetxt() in the example specifies that the numbers are integers. You can use a different format for each column. E.g. to specify floating point format, with 2 decimal digits and 10 characters wide columns, you would use '%10.2f'.

like image 19
Fabio Avatar answered Oct 17 '22 18:10

Fabio