# How to define a function to save a list to a same-name file

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?

• Try SetAttributes[tablesaveFunction, HoldAll]. – N.J.Evans Jun 18 '15 at 15:42
• Same result.... – Chromatic Jun 18 '15 at 16:03
• Look up DumpSave in the documentation (and on this site)... – MikeLimaOscar Jun 18 '15 at 16:09
• Remove[tablesaveFunction]; SetAttributes[tablesaveFunction, HoldAll]; tablesaveFunction[x_] := Export[ToString@#1 <> ".dat", #2] &@@x; works for me, but you end up writing the table with the head HoldForm which may not be acceptable. – N.J.Evans Jun 18 '15 at 16:16

## 2 Answers

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}} *)

• This works, though I may use DumpSave, thanks to @MikeLimaOscar – Chromatic Jun 18 '15 at 17:02
• @Chromatic I think DumpSave would indeed be a good idea especially if your tables are massive. Nevertheless, it's probably still better to use the SymbolName approach, rather than Trace, to get to the symbol's name. – MarcoB Jun 18 '15 at 17:19
• @Chromatic, if you think that my answer above adequately addresses your problem, would you consider formally accepting it by clicking on the grey check mark next to it? – MarcoB Jul 13 '15 at 19:04

Instead of starting with the symbol table1 and trying to extract the name of it and convert it to a string, why not give the string as the function argument and use ToExpression inside the function to access the variable?

exportTable[s_String] := Export[s <> ".dat", ToExpression@s]


You call this with a string with the same name as the table you want to export:

exportTable["table1"]