简体   繁体   中英

Use text file to save and read array

I have an array which has many arrays in it which have many arrays in them, ie, a large nested array.

I'd like to store this giant array in a text file to later be used by another python program - one python program produces the array and saves it to the text file, while another opens the text file and saves it to its own local array.

In other words, this large nested array has to be identical for both programs.

How exactly should I do this?

I would suggest using the pickle module instead of a text file:

Saving an array:

import pickle as pkl
arr = [...]
with open('save.pkl', 'wb') as f:
    pkl.dump(arr, f)

Opening it again:

with open('save.pkl', 'rb') as f:
    arr = pkl.load(f)

If you really want to use a text file you can use literal_eval() from ast to change the text to an array:

from ast import literal_eval
with open('mydata.txt') as f:
    arr = literal_eval(f.read())

And then changing the array:

with open('mydata.txt', 'w+') as f:
    f.write(str(arr))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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