I have many (say 2 for now) associations that I want to save to a file
<|"A" -> 1 , "B" -> 2|> >>> NotebookDirectory[] <> "TEST.m"
<|"A" -> 11 , "B" -> 22|> >>> NotebookDirectory[] <> "TEST.m"
Now I would like to somehow get all this expressions into a list, obtaining
{<|"A" -> 1 , "B" -> 2|>,<|"A" -> 11 , "B" -> 22|>}
But if I do
loaded = Get[NotebookDirectory[] <> "TEST.m"]
I obtain only the last one
<|"A" -> 11 , "B" -> 22|>
What is the correct thing to do?
Answer
Your file does contain the expressions you saved but Get evaluates the file rather than importing the lines as expressions. The latter can be done with Import:
Import["TEST.m", "ExpressionList"]
{<|"A" -> 1, "B" -> 2|>, <|"A" -> 11, "B" -> 22|>}
Alternatively you could also save a definition rather than the bare expressions. See:
As Albert Retey comments I failed to mention that the behavior in this case is not related to Association but only the mechanics of PutAppend and especially Get. The same behavior would be seen for any series of standard expressions.
An additional note: the Import command above evaluates expressions (like Get) but also returns a list of them. If you wish to only return a list without evaluating at all you can use:
Import["file.m", "HeldExpressions"]
Each expression will be returned wrapped in HoldComplete.
These Import elements are described in the documentation for the Package format.
Comments
Post a Comment