Chip Burwell Chip Burwell - 18 days ago 6
Python Question

Parse text position vector to floats

I have a .txt file that contains lines in this format:


Because I have lots of other lines that start with an open bracket and a name enclosed in quotes followed by a semi-colon, I have split the line into two like this:

[ '{"Position":', '[81.2305,4.05698,9.14912]}' ]

I would like to parse the second string into a list of 3 floats. What is the best way to do this?


Your data looks like JSON, so you can use the built-in JSON module:

import json

pos = [] # list of (x,y,z)

with open('t.txt') as infile:
    for line in infile:
        # skip blank lines (add other cases as needed)
        if not line.strip():

        item = json.loads(line)
        if "Position" in item: