I want a convenient way to save lots of intermediate data lists into files, so that next time the files can be imported automatically to homonym list variables in the notebook, without having to evalutate some time-consuming intermediate steps again.
I can already use the following expression to export table1 to a file of same name.
table1 = {{1, 2}, {3, 4}};
Export[ToString@((Trace@table1)[[1]]) <> ".dat", table1]
Then I define a table-saving function in this way:
tablesaveFunction := Export[ToString@((Trace@#)[[1]]) <> ".dat", #] &
tablesaveFunction[table1]
what I get is:
Part::partw: Part 1 of {} does not exist. >>
{}[[1]].dat
I guess the problem is about the order of evaluation, but do not know how to solve.
Or, any other easy methods to achieve my goal?
Answer
You need to set a Hold attribute for your function, as @N.J.Evans mentioned as well. Also, instead of using Trace to obtain the symbol name, try using SymbolName instead:
Clear[exportTable]
SetAttributes[exportTable, HoldFirst]
exportTable[t_] := Export[SymbolName[Unevaluated[t]] <> ".dat", t]
exportTable[table1]
You can then re-import your table at will:
Import["table1.dat"]
(* Out: {{1, 2}, {3, 4}} *)
Comments
Post a Comment