PanAkry
PanAkry

Reputation: 183

write in file with python

I am searching for the easiest way to save an array in a file. For this I would want to use numpy.savetxt but the problem is that my array is composed of n columns (the number depends on what i ant to do) and it contains complex elements (x+yj). I know how to save it if there is one column and real elements but I don't know how to do.

Does anybody have an idea?

Upvotes: 0

Views: 2683

Answers (1)

strcat
strcat

Reputation: 5612

You could pickle them:

>>> A = np.array([[1,2],[3,4+2j]])
>>> pickle.dump(A, open("out.pkl", "wb"))
>>> pickle.load(open("out.pkl", "rb"))
array([[ 1.+0.j,  2.+0.j],
       [ 3.+0.j,  4.+2.j]])

However, it would be better to use numpy.save and numpy.load, they're designed for this and will use a lot less space.

>>> np.save("out.npy", A)
>>> np.load("out.npy")
array([[ 1.+0.j,  2.+0.j],
       [ 3.+0.j,  4.+2.j]])

Upvotes: 2

Related Questions