0

I have an array which has many arrays in it which have many arrays in them, i.e, 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?

3
  • Are you sure yu want to use text files? Why don't you go with some binary serialization method: since you are in python and want a transfer between python instances you may use pickle... Commented May 1, 2018 at 17:52
  • learnpython.org/en/Serialization Commented May 1, 2018 at 17:52
  • Use Numpy and its respective functions for dealing with saving and loading arrays. Commented May 1, 2018 at 17:53

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I decided to use pickle. When I implemented your code, the write code seemed to work, but the read code outputs this error: TypeError: a bytes-like object is required, not '_io.TextIOWrapper'
I'm so sorry I made a typo. It should be pickle.load not loads. It has been edited.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.