简体   繁体   English

保存python个数组元素到txt文件

[英]Saving python array elements to txt file

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:我想将两个一维 arrays 保存为文本文件中的两列,以便稍后能够打开此文件和 plot 其中一列我使用了以下内容:

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现在,当查看 output 文件时,我看到 arrays 存储为

[  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?我的问题是如何将数组元素保存为 txt 文件中的列?

if it's only to save data for another run you can use pickle :如果只是为另一次运行保存数据,您可以使用pickle

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

you can save in txt file like that:你可以像这样保存在txt文件中:

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

I used Pandas to save the data as DataFrame in a csv file,我使用 Pandas 将数据保存为 DataFrame 在 csv 文件中,

dict = {'s_pos': s_pos, 'beta_x': beta_x, 'beta_y': beta_y,
            'dx': dispersion_x, 'dy': dispersion_y, 'closed_orbitx': closed_orbitx, 'closed_orbity': closed_orbity}

    df = pd.DataFrame(dict)

    # saving the dataframe
    df.to_csv('directory/twiss.csv')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM