2

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?

lurscher
  • 743
  • 3
  • 13
  • 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 <<. – Mr.Wizard Oct 31 '14 at 07:30
  • 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 – lurscher Oct 31 '14 at 07:35
  • 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? – Mr.Wizard Oct 31 '14 at 07:42
  • Also, did you read my answer? Therein I explain why this behaves as it does. – Mr.Wizard Oct 31 '14 at 07:44

1 Answers1

2

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

Nasser
  • 143,286
  • 11
  • 154
  • 359
  • it does indeed work with Put, but with Get I get: "Cannot open Evaluate" – lurscher Oct 31 '14 at 06:38
  • @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. – Nasser Oct 31 '14 at 06:42