How to import a matrix in txt file to python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to import a matrix in txt file to python?

I have some matrix in text file...want to import as a variable

29th Jan 2017, 8:29 PM
voryamiraki
voryamiraki - avatar
3 Answers
+ 2
# open() and eval() may be a starting point # for research into this and other options pro's and cons # of persistent data handling. # Simple example. # in a text file called text_to_variable.txt # if your text file contains a single line of text # such as # [[3,4,5],[3,4]] my_matrix = None with open('text_to_variable.txt','r') as my_file: my_matrix = eval(my_file.read()) print(my_matrix,type(my_matrix))
30th Jan 2017, 2:14 AM
richard
+ 1
You would have to read the text from the file, interpret it and then append it to the variable, it's hard to tell you how since we don't know what the file or code looks like. I assume if you have a textfile that you formed as a matrix you can read it line by line and append it to the variable, or presumably into a 4,4 array.
29th Jan 2017, 8:37 PM
Alex
Alex - avatar
0
thanks for ur helps....
31st Jan 2017, 9:23 PM
voryamiraki
voryamiraki - avatar