Write array to .txt-file

Question:

In Python I need to write a list of numpy-arrays (see attached picture) to a txt.-file and then reuse that original list of arrays in a new python-file. How can I do that?

enter image description here

read_files = open("read_files.txt","w+")

content = str(df)

read_files.write(content)
read_files.close()

Then in the new python-file I did:

file = open("read_files.txt", "r")
content = file.read()

But when I want to slice the list of arrays in the new python-file I get the following error:

TypeError: string indices must be integers
Asked By: yessir22

||

Answers:

Use np.save for 3D arrays:

arr = np.random.random((20, 10, 5))

np.save('arr', arr)  # extension .npy

arr2 = np.load('arr.npy')

Note: the file is not human readable.

Output:

>>> np.all(arr2 == arr)
True
Answered By: Corralien
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.