Skip to content Skip to sidebar Skip to footer

How To Read Array Of Numbers From Text File In Python

I have written code as: array = [[1.630217208498539], [0.019929319226538452]] fo = open('file.txt', 'w') fo.write(str(array)) fo.close() That will save the array in .txt file, th

Solution 1:

 import pickle

 numlist = [[1.630217208498539], [0.019929319226538452]] 

 outfile = open("log.txt", "wb")

 pickle.dump(numlist, outfile)

 outfile.close()

 infile = open("log.txt", "rb")

 pickle.load(infile)
 [[1.630217208498539], [0.019929319226538452]] 

Solution 2:

use ast.literal_eval(node_or_string) to evalute the string expression:

In [238]: import ast

In [241]: my_array=ast.literal_eval('[[1.630217208498539], [0.019929319226538452]]')

In [242]: my_array
Out[242]: [[1.630217208498539], [0.019929319226538452]]

Post a Comment for "How To Read Array Of Numbers From Text File In Python"