I have in my job many times to parse ASCII headers of files from instruments and most of the time I do that interactively with the IPython console. Usually, I have a header that looks like this:
range = 55
param1 = 0.1
comment = "this is a comment"
parm2 = 0.4
values = [1,2,3,4]
I usually split and take the values on the right, but I want to cast them to the python type that best represent them e.g. [1,2,3,4]
I don't want a string but a list.
I would like to convert automatically the values to the closest Python type that they can assume (immagine that later I've to add parm1
to parm1
of another file or zip values
of two file together), this is a test case:
var = "this should not be displayed!"
testcases = ["55 "," 0.1","[1,2,3]","{1,4,5}","comment comment","'scanning type!'",'{"key": "value"}','""','None','also this is valid',"var"]
I usually use this approach but I have to write a try and except (this for Python3 because of the except):
import ast
for test in testcases:
try:
test = ast.literal_eval(test.strip())
except(SyntaxError, ValueError) as g:
test = test.strip()
print(test)
Is there any better approach without try and excepts and using the standard Python library or common scientific library (numpy,scipy, pandas) that output the same output of the function I've written? This would speed up a lot my job.