I have been able to write to a file using the Put[] function.
Once I write to the file, I can look at it via software like notebook or Mathematica itself.
So far, so good.
However, I would now like to programmatically read the contents of the file, and therein lies the issue.
When I create a file name as in filename = “somefilename”,
I can read it with: data = Get[filename]
I can also read it with data = << “somefilename” (* where I literally type the name of the file in quotes*)
And in the last 3 statements, which are in a function, the variable filename is defined in a Module as
Function[] := Module[{filename}, …]
And the variable “filename” appears in GREEN, telling me that it is, indeed, recognized as a local variable.
BUT, when I try to read the file with: data = << filename;
I get the error: “Get::noopen: Cannot open filename1.”
What I don’t understand is why 3 statements, that to me are equivalent, provide such different results;
Why is it that:
data = Get[filename]; (* WORKS !)
data = << “somefilename”; ( The string value of the variable filename, WORKS! )
But
data = << filename; ( Not only DOESN"T WORK, but the variable filename is not in GREEN (local variable) but is show in black (global variable, even though I don’t have a global variable called filename.
Can someone explain this behavior to me?
It seems that << WORKS if you pass it a file name as a string on the right hand side (RHS) as in:
data = << “some filename expressed as a string”
and FAILS if you give it a variable name on the RHS as in data = << variableName
It is probably something simple, but I can’t get the nuance.
ClearAll[x, a];
a = Sin[x];
Put[a, "foo"]
ClearAll[x, a]
a = << "foo"
(* Sin[x] *)
ClearAll[x, a]
foo = "foo";
a = << foo
(* Sin[x] *)
Please provide a specific example that demonstrates the failure. Also please use the code formatting button to format code. Read the “Code Formatting” section here .
See the note in the documentation page for Get that says
<<“name” is equivalent to <<name. The double quotes can be omitted if the name contains only alphanumeric characters and the characters `, /, ., ∖, !, -, _, :, $, *, ~, and ?, as described in greater detail in “Operator Input Forms”.
Thank you Jason. Your explanation makes it clear.
However I now think that it is really confusing to have <<“name” equivalent to <<name
What if I want to change the filename and put it in a variable so that << name could output to one file at one point and then, after doing name = “otherfilename”, I want to again do << name?
I guess I will have to use the Get[filename] approach all the time.
Thank you Jason.
Now to find out how to mark your reply as the definitive answer.