0
$\begingroup$

I am importing data which are formatted as a list containing lists. And I would like to keep these data in this format.

Export["data.dat",{{1,{1,2,3}},{2,{3,4,5}}]
data=Import["data.dat"]

However, if I simply do that, Mathematica seems to consider the lists inside the list as strings so I tried:

data=ToExpression[Import["data.dat"]]

In this case Mathematica fails and gives the following error:

ToExpression::sntxi: Incomplete expression; more input is needed .
ToExpression::sntx: Invalid syntax in or before "2, ".

Actually doing some manipulations I realized that when you just import the list into Mathematica, it takes:

{{1, "{1,", "2,", "3}"}, {2, "{3,", "4,", "5}"}}

Any idea on how to convert this strange expression into the list I initially had?

$\endgroup$
2
$\begingroup$

You don't want to export to a .dat file if are going to read the file back into Mathematica. Better to use the extension .m for in that case.

path = FileNameJoin[{$HomeDirectory, "Desktop", "data.m"}]
Export[path, {{1, {1, 2, 3}}, {2, {3, 4, 5}}}];

data = Import[path]

{{1, {1, 2, 3}}, {2, {3, 4, 5}}}

But this can be done more easily with

Put[{{1, {1, 2, 3}}, {2, {3, 4, 5}}}, path]
Get[path]

{{1, {1, 2, 3}}, {2, {3, 4, 5}}}

$\endgroup$
  • $\begingroup$ This was exactly what I was looking for. Thank you very much :) $\endgroup$ – Sennin Oct 26 '17 at 11:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.