Saving a numpy array in ascii format

47 Views Asked by At

I have data in form of a 2D array.

my_array = np.array([[1,2,3],[4,5,6])

How can I save the data as an ascii-file?

Furthermore: Is it problematic if the array contains a large amount of data?

I know how to save as data as a txt file, but that is not what I want or at least I would need to change the settings somehow.

1

There are 1 best solutions below

2
tax evader On

You can use np.savetxt function for that. For loading the text file, you can use np.loadtxt

import numpy as np

a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
np.savetxt('saved_array.txt', a)

b = np.loadtxt('saved_array.txt')
print(a == b) # validation step

Alternatively, you can also just write a printable representational string into a text file using regular built-in python IO

import numpy as np

a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])

with open('saved_array.txt', 'w') as fl:
    fl.write(repr(a))