3
$\begingroup$

Example:

I save data to a MX file, like:

a=Range[100]; b=Range[1000]; Export["data.mx", {a,b}, "MX"]; 

Can I after importing the data:

data = Import["data.mx", "MX"]; 

also retrieve the names of the variables a,b?

$\endgroup$
2
  • 3
    $\begingroup$ related: DumpSave for the forgetful $\endgroup$ Commented May 10, 2017 at 13:20
  • $\begingroup$ great link, thank you. $\endgroup$ Commented May 10, 2017 at 13:24

1 Answer 1

4
$\begingroup$

No, because those names were never saved into the file.

If you want the names saved too, you can use DumpSave instead of Export for saving, and Get instead of Import for loading. In this case, a and b will be overwritten upon Get. I do not like this method because I need to remember those names, and because I consider overwriting dangerous.

Personally I would export an association instead of a list:

<|"a" -> a, "b" -> b|> 

This way I can make the structure of the data self-explanatory.

$\endgroup$
4
  • $\begingroup$ Could I do this: Export["data.mx", <|"a" -> a, "b" -> b|>, "MX"];? and reading would be: data = Import["data.mx"]? After reading how do I assign a=... and b=...? $\endgroup$ Commented May 10, 2017 at 13:57
  • $\begingroup$ @lio Yes, that is what I meant I would do. But the whole reason why I suggested associations was to avoid assigning. If you want to assign a and b after reading, then I suggest you use DumpSave/Get. $\endgroup$ Commented May 10, 2017 at 13:59
  • $\begingroup$ Thank you for the explanation ... $\endgroup$ Commented May 10, 2017 at 19:36
  • $\begingroup$ @lio To be fair, you can set values based on an association, but it requires something a bit more advanced: setName[name_String, value_] := ToExpression[name, InputForm, Function[s, s = value, HoldAll]] Now setName["a", 1] sets the value of a to 1. So you can do KeyValueMap[setName, <|"a" -> 1, "b" -> 2|>] to set a to 1 and b to 2. $\endgroup$ Commented May 10, 2017 at 19:40

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.