1

I have two text files that have matrices written in them(not numpy matrices, so its a list of lists). These matrices are written in string format, so the text file looks like this : [[1,2,3],[3,4,5],[6,7,8]],[[3,3,3],[5,6,7],.....

I want to read this matrix back from the text file using python. I can't read using numpy as it gives ValueError: could not convert string to float

Is there anyway to do this? Would it be easier if I just wrote the matrix as a numpy matrix in the first place(I need to change code of a previous program for that, and was just wondering if there was a python way of loading matrices when it was stored as a string in a text file)?

3
  • do you have an example of the code you have tried Commented May 23, 2014 at 5:55
  • I tried numpy.load("file.txt"), but like I said that didn't work. I guess there might be a way to do it by setting custom delimiters in readline(), but how you handle the "[" and other string characters? Also, I'd prefer to use a simple method if there is one. Commented May 23, 2014 at 5:58
  • have you tried the pickle module for python? it saves python objects for you so you could just save the lists to a file then reload them. Commented May 23, 2014 at 6:05

1 Answer 1

2

You could make use of the ast module:

import ast

strArray =  "[[1,2,3],[3,4,5],[6,7,8]]"

# evaluates the array in string format and converts it to a python array object
array = ast.literal_eval(strArray)

note: For multiple nested arrays like you have, literal_eval will most likely convert the string into a tuple with nested arrays as elements. Just keep that in mind as you use this module.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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