Kathryn Parr Kathryn Parr - 4 months ago 8
Python Question

I need to write 3 arrays to a text file in columns

The arrays are as below

array1=np.array([1.5397e-05,8.7383e+00,2.6633e+01,1.1309e+03,4.3194e+02,2.5086e+01])
array2=np.array([4.83,1.4,0.4,-7.2,-3.64,0.6])
array3=([‘Sun’,’Sirius’,’Arcuturus’,’Betelgeuse’,’Polaris’,’Vega’])


I would like the data to look like the information below in a text file called star.txt.

Sun 1.5397e-05 4.83
Sirius 8.7383e+00 1.4
Arcuturus 2.6633e+01 0.4
Betelgeuse 1.1309e+03 -7.2
Polaris 4.3194e+02 -3.64
Vega 2.5086e+01 0.6


Can anyone please help?

Answer

How's this?

import numpy as np

array1=np.array([1.5397e-05,8.7383e+00,2.6633e+01,1.1309e+03,4.3194e+02,2.5086e+01])
array2=np.array([4.83,1.4,0.4,-7.2,-3.64,0.6])
array3 = ['Sun','Sirius','Arcuturus','Betelgeuse','Polaris','Vega']

with open('star.txt', 'w') as f:
    for a, b, name in zip(array1, array2, array3):
        f.write('{0:15}{1:15}{2:15}\n'.format(name, a, b))

Output

File star.txt in same folder with the following contents:

Sun                 1.5397e-05           4.83
Sirius                  8.7383            1.4
Arcuturus               26.633            0.4
Betelgeuse              1130.9           -7.2
Polaris                 431.94          -3.64
Vega                    25.086            0.6

For the record it would be nice if you used more descriptive variable names than array1, array2, etc. so that I could use more descriptive variable names than a, b, etc.