1

I am trying to read an array from file which I made earlier and then assign it to variable. But now i ran into a problem. When i assigned that file content to variable, it became string instead of array. how do i convert that back to an array ?

file.txt content:

[(0, 0.2, ),(0, 0.1, ),(0.2, 0.2, ),(0.2, 0.2, ),(0.4, 0.2, ),]

my code:

valid_outputs = f=open("fileName.txt","r")
if(f.mode == 'r'):
    valid_outputs = f.read()
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • That's not an array, it's a Python `list` with `tuple` values. Not sure how you managed to produce that exact string however, as the Python representation would not include the trailing commas. – Martijn Pieters Aug 16 '19 at 15:07

3 Answers3

1

You could use ast.literal_eval() on the string:

>>> ast.literal_eval('[(0, 0.2, ),(0, 0.1, ),(0.2, 0.2, ),(0.2, 0.2, ),(0.4, 0.2, ),]')
[(0, 0.2), (0, 0.1), (0.2, 0.2), (0.2, 0.2), (0.4, 0.2)]
Sam Mason
  • 15,216
  • 1
  • 41
  • 60
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

Slightly convoluted, but without any packages:

>>> [tuple([float(i) for i in block.split(",")[:2]]) for block in valid_outputs.replace(")]", "").replace("[(", "").split("),(")]
[(0.0, 0.2), (0.0, 0.1), (0.2, 0.2), (0.2, 0.2), (0.4, 0.2)]
tituszban
  • 4,797
  • 2
  • 19
  • 30
0
x = None
with open("file.txt", "r") as f:
    x = eval(f.read())

print x
Sam Daniel
  • 1,800
  • 12
  • 22