This seems like a simple question, but couldn't find it on the Stack community. I have a dataset like the one below in a text file. I would like to read it in as a list with each value as a float. Currently the output is very odd from the simple list needed (also below).
data.txt:
[1130.1271455966723, 1363.3947962724474, 784.433380329118, 847.2140341725295, 803.0276763894814,..]
Code attempted:
my_file = open(r"data.txt", "r")
content = my_file.read()
content_list = content.split(",")
my_file.close()
The output is odd. The values are string and list inside of list and added spaces:
Current result:
['[1130.1271455966723',
' 1363.3947962724474',
' 784.433380329118',
' 847.2140341725295',
' 803.0276763894814',
' 913.7751118925291',
' 1055.3775618432019',...]']
I also tried the approach here (How to convert string representation of list to a list?) with the following code but produced an error:
import ast
x = ast.literal_eval(result)
raise ValueError('malformed node or string: ' repr(node))
ValueError: malformed node or string: ['[1130.1271455966723', '1363.3947962724474', ' 784.433380329118', ' 847.2140341725295', ' 803.0276763894814',...]']
Ideal result:
list = [1130.1271455966723, 1363.3947962724474, 784.433380329118, 847.2140341725295, 803.0276763894814]
CodePudding user response:
Your data is valid JSON, so just use the corresponding module that will take care of all the parsing for you:
import json
with open("data.txt") as f:
data = json.load(f)
print(data)
Output:
[1130.1271455966723, 1363.3947962724474, 784.433380329118, 847.2140341725295, 803.0276763894814]