Arthur Plante
Arthur Plante

Reputation: 269

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

Upvotes: 24

Views: 123779

Answers (6)

Fabio
Fabio

Reputation: 1220

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

Upvotes: 21

Ashok Kumar Jayaraman
Ashok Kumar Jayaraman

Reputation: 3085

You can write two lists into a text file that contains two columns.

a=[1,2,3]
b=[4,5,6] 
c = [a, b] 
with open("list1.txt", "w") as file:
    for x in zip(*c):
        file.write("{0}\t{1}\n".format(*x))

Output in the text file:

1   4
2   5
3   6

Upvotes: 1

SpinUp __ A Davis
SpinUp __ A Davis

Reputation: 5531

A simple solution is to write columns of fixed-width text:

a=[1,2,3]
b=[4,5,6]

col_format = "{:<5}" * 2 + "\n"   # 2 left-justfied columns with 5 character width

with open("foo.csv", 'w') as of:
    for x in zip(a, b):
        of.write(col_format.format(*x))

Then cat foo.csv produces:

1    4    
2    5    
3    6    

The output is both human and machine readable, whereas tabs can generate messy looking output if the precision of the values varies along the column. It also avoids loading the separate csv and numpy libraries, but works with both lists and arrays.

Upvotes: 4

Aurelien Sanchez
Aurelien Sanchez

Reputation: 1

It exits a straightway to save and stack same vectors length in columns. To do so use the concatenate function, you can then stack 3,4 or N vectors in columns delimitered by a tab.

np.savetxt('experimental_data_%s_%.1fa_%dp.txt'%(signal,angle,p_range), np.c_[DCS_exp, p_exp], delimiter="\t")

Upvotes: 0

Syed Farjad Zia Zaidi
Syed Farjad Zia Zaidi

Reputation: 3360

Try this:

file = open("list.txt", "w")
for index in range(len(a)):
    file.write(str(a[index]) + " " + str(b[index]) + "\n")
file.close()

Upvotes: 7

Burhan Khalid
Burhan Khalid

Reputation: 174624

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

Upvotes: 27

Related Questions