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
  • 963,270
  • 265
  • 3,804
  • 3,187
  • 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
  • 12,674
  • 1
  • 33
  • 48
NPE
  • 464,258
  • 100
  • 912
  • 987
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
  • 3,909
  • 1
  • 18
  • 27
0
x = None
with open("file.txt", "r") as f:
    x = eval(f.read())

print x
Sam Daniel
  • 1,625
  • 11
  • 21