Home > Back-end >  Saving python array elements to txt file
Saving python array elements to txt file

Time:03-03

I want to save two one-dimention arrays as two columns in a text file to be able later to open this file and plot one of these columns I used the followng:

file = open("myfile.txt", "w")
    print(s, beta,, file=file)
    file.close()

Now when look at the output files i saw the arrays stored as

[  1.4    4.31   7.21  10.12  13.02  15.93  18.83  21.74  24.64  27.55
  30.45  33.36  36.26  39.17  42.07  44.98  47.88  50.79  53.69  56.6
  59.5   62.41  65.31  68.22  71.12  74.03  76.93  79.84  82.74  85.65
  88.55  91.46  94.36  97.27 100.17 103.08 105.98 108.89 111.79 114.7 ] [5.7882581  3.09619004 5.7882581  3.09619004 5.7882581  3.09619004
 5.7882581  3.09619004 5.7882581  3.09619004 5.7882581  3.09619004
 5.7882581  3.09619004 5.7882581  3.09619004 5.7882581  3.09619004
 5.7882581  3.09619004 5.7882581  3.09619004 5.7882581  3.09619004
 5.7882581  3.09619004 5.7882581  3.09619004 5.7882581  3.09619004
 5.7882581  3.09619004 5.7882581  3.09619004 5.7882581  3.09619004
 5.7882581  3.09619004 5.7882581  3.09619004]

So i tried to convert the array row into a columns:

 file = open("myfile.txt", "w")
        print(s.T, beta.T,, file=file)
        file.close()

And i still can not see a change,

My question is how to save the array elements as a column in a txt file ?

CodePudding user response:

if it's only to save data for another run you can use pickle:

import pickle
with open("data.pickle", "wb") as file:
    pickle.dump(YOUR_LIST, file)

you can save in txt file like that:

with open("myfile.txt", "w") as file:
    for line in YOUR_LIST:
        file.write(" ".join(line))

CodePudding user response:

I used Pandas to save the data as DataFrame in a csv file, .

  • Related