2
$\begingroup$

I'm trying to do the following with an expression:

filename=StringJoin[{"myfile", ToString[someNumber],".m"}];
expression >> filename;

But mathematica keeps creating a file named "filename", instead of "myfile42.m"

Any idea how can I tell Put to pretty please, use the filename string value, instead of the expression's name?

$\endgroup$
4
  • $\begingroup$ I have answered this question previously so I am marking this one as already has an answer. Please see the link inserted at the top of your post. In short use Put rather than >> and Get rather than <<. $\endgroup$
    – Mr.Wizard
    Commented Oct 31, 2014 at 7:30
  • $\begingroup$ In fact @Mr.Wizard I tried using the Put and Get form and the problem persisted. The correct solution was the one suggested by @Nasser using Evaluate $\endgroup$
    – lurscher
    Commented Oct 31, 2014 at 7:35
  • $\begingroup$ What version are you using and what is the output of Attributes[{Get, Put}]? On my machine it is {{Protected}, {Protected}}. That means these do not have Hold attributes and therefore filename will be evaluated. What exactly did you try? $\endgroup$
    – Mr.Wizard
    Commented Oct 31, 2014 at 7:42
  • $\begingroup$ Also, did you read my answer? Therein I explain why this behaves as it does. $\endgroup$
    – Mr.Wizard
    Commented Oct 31, 2014 at 7:44

1 Answer 1

2
$\begingroup$

Put seems to treat the argument as literal and not evaluate it. i.e. it takes the argument filename as the actual filename and not its value. In Mathematica talk, this is called Holding its arguments.

Just do this:

  expression >> Evaluate@filename

Should work. Worked for me. Full example:

SetDirectory[NotebookDirectory[]];
somenumber = 10;
filename = StringJoin[{"myfile", ToString[somenumber], ".m"}];
2 >> Evaluate@filename
x = Get[Evaluate@filename];
x

Mathematica graphics

$\endgroup$
2
  • $\begingroup$ it does indeed work with Put, but with Get I get: "Cannot open Evaluate" $\endgroup$
    – lurscher
    Commented Oct 31, 2014 at 6:38
  • $\begingroup$ @lurscher make sure your notebook is in same directory where you save the file? It works for me !Mathematica graphics just do SetDirectory[NotebookDirectory[]] before exporting. $\endgroup$
    – Nasser
    Commented Oct 31, 2014 at 6:42

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