0

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)

2
  • 1
    Try ast.literal_eval() Commented Feb 18, 2014 at 7:16
  • The term for what you're looking for is "serialization", and python provides many ways to do that, the most popular being pickle (for native python data) and json (for cross-platform data). Commented Feb 18, 2014 at 9:32

2 Answers 2

2
 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]] 
Sign up to request clarification or add additional context in comments.

2 Comments

"accept it" is hardly acceptable
@Avinash Garg yes it is working but in txt file it is not loading in proper array pattern, it is showing as:(lp0 (lp1 F1.630217208498539 aa(lp2 F0.019929319226538452 aa. is there any way to correct it
0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.