I need to know if I can easily assign a variable within my script from a declaration in a text file. Basically, I want the user to be able to change the variable via the text file to match the numbers needed without having to fiddle with the source code.
Text file input format:
faultInfo = [
[["L1603",1,5],[271585,972739],[272739,872739, 272739,972739, 271585,972739, 271585,272389, 270999,272389]],
[["L1605",1,5],[271897,872739],[272739,872739, 272739,972739, 271891,872739, 271891,272119, 270963,272119]],
[["L1607",1,4],[271584,272738],[271584,272738, 271584,272388, 270998,272388, 270998,272386]]
]
I simply want to load this into a list variable with the same name in my script. I am new to Python and not a CS major or anything. I know I could load the 3-D list using loops and whatnot, but it seems like there should be a quick way to do this since the size of the k'th dimension is jagged and will change from case to case.
Thanks in advance.
Thanks
This data looks simple enough that you can parse it using either json.loads
or ast.literal_eval
(both in the standard library):
>>> a = """[
... [["L1603",1,5],[271585,972739],[272739,872739, 272739,972739, 271585,972739, 271585,272389, 270999,272389]],
... [["L1605",1,5],[271897,872739],[272739,872739, 272739,972739, 271891,872739, 271891,272119, 270963,272119]],
... [["L1607",1,4],[271584,272738],[271584,272738, 271584,272388, 270998,272388, 270998,272386]]
... ]
...
... """
>>> import ast
>>> ast.literal_eval(a)
[[['L1603', 1, 5], [271585, 972739], [272739, 872739, 272739, 972739, 271585, 972739, 271585, 272389, 270999, 272389]], [['L1605', 1, 5], [271897, 872739], [272739, 872739, 272739, 972739, 271891, 872739, 271891, 272119, 270963, 272119]], [['L1607', 1, 4], [271584, 272738], [271584, 272738, 271584, 272388, 270998, 272388, 270998, 272386]]]
>>> import json
>>> json.loads(a)
[[[u'L1603', 1, 5], [271585, 972739], [272739, 872739, 272739, 972739, 271585, 972739, 271585, 272389, 270999, 272389]], [[u'L1605', 1, 5], [271897, 872739], [272739, 872739, 272739, 972739, 271891, 872739, 271891, 272119, 270963, 272119]], [[u'L1607', 1, 4], [271584, 272738], [271584, 272738, 271584, 272388, 270998, 272388, 270998, 272386]]]
You could easily get the string (a
in my example) from file.read()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With