Setup: I start with a non-square 2-dimensional list of values:
list = [ ['A','B','C'], np.array([1, 2, 3, 4]), np.array([0.5, 1.5]) ]
This list is then written to a file. Later, I need to extract this same list from the file to do work on.
Current method: I handle writing in an extremely simple manner: str()
and f.write()
commands. Part of this is that it was easy to set up; part of it is because the same file contains other, non-list objects which are being written (strings, dicts, ints, etc). I am running into trouble on the other end, however, when I load the file. The most direct approach gives
loadList = list(stringFromFile)
print(loadList)
> [ "[" "[" "'" "A" "'" "," "'" "B" "'" ...
and so on. Clearly, not what I am looking for. Adding in a splitter does a little better:
loadList = list(stringFromFile.split(','))
print(loadList)
> [ "[['A'" , "'B'" , "'C']" , "np.array([1", "2", "3", "4])", "np.array([0.5", "1.5"])]" ]
...but mishandles the subdivisions. Redefining the splitter (...split('],')
) mishandles the array() elements, and so on.
Following this path, I can see a way to make it work with a significant number of if
catches, a carefully refined splitter, and some special cases. However, it feels very clunky to do it in this manner. I also question whether it will be generalizable to any oddly-constructed 2-dimensional list-like that users might throw at it.
Is there a more elegant way to implement this? I am open to changing my write method, read method, or both, but I cannot change the handling of the list object itself without some pretty drastic redesign of the entire program.