简体   繁体   中英

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, the content in the .txt file is in 2d array as:

[[1.630217208498539], [0.019929319226538452]]

And I want this array as it is back to the another program so that i can use this array for further calculation (the read array should not be a string)

 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]] 

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM