Search code examples
pythonsparse-matrix

How to write a sparse matrix in a text file in python?


I have a sparse matrix as A_n. type of A_n is "scipy.sparse.csc.csc_matrix".

for example, A_n is:

(16, 0) 1.0
(71, 1) 1.0
(74, 3) 1.0
(72, 12)    1.0
  .          .
  .          .
(32, 17)    1.0
(64, 17)    1.0
(53, 19)    1.0
(73, 20)    1.0
(52, 21)    1.0
(52, 22)    1.0
(44, 26)    1.0
(53, 26)    1.0
(87, 26)    1.0

I want to write all of A_n in a text file in python as follows:

16 0 1.0
71 1 1.0
74 3 1.0
.
.

or

(16, 0) 1.0
(71, 1) 1.0
(74, 3) 1.0
.
.

I would be very grateful if you guide me


Solution

  • You could simply convert the spare matrix object to a string using str(sparse_matrix) and then write it to a file after changing the maxprint attribute to spare_matrix.shape[0].

    sparse_matrix.maxprint = sparse_matrix.shape[0]
    with open("spare_matrix.txt","w") as file:
        file.write(str(sparse_matrix)) 
        file.close()