Carl has shown a way to write to the file what you want, but I would suggest to not even put the terms=
into the file: you can read the expression and set it to a variable when reading it. It will also get rid of all kinds of complications that occure if you want to write partially evaluated expressions. This approach lets you choose the name of the variable at the time of reading which I think is an advantage as it will make it somewhat simpler to e.g. compare the content of two such files in one session.
As for the directory using SetDirectory
is also a perfectly valid solution, but I would suggest to just use full pathes for the files which gives you more control about the location and is much easier to understand and debug, as it is "free" of the current "state" of what the working directory is set to. This is what I'd do:
f[x_] := Expand[(a + b)^100];
fname = FileNameJoin[{NotebookDirectory[], "Terms.m"}];
Put[f[x], fname];
using NotebookDirectory
will store "Terms.m" in the same directory as the notebook this is running in, which is very often what you want. You can of course use whatever other directory you want. I'd suggest to look through the predefined directories instead of typing in long machine specific directory names, there are e.g. variables for your home directory, the temporary directory or your documents directory. You can find all predefined directory names by evaluating this:
?$*Directory*
If you already have evaluated f[x]
and don't want to rerun it, you might want to use something like:
Put[%,fname]
if the output was the last result calculated. Using something like the following is more robust, as it is independent on how many other things have been evaluated since the call to f[x]
:
Put[Out[123],fname]
where the output number (123 in the example) you can read from the output cell tag (these labels can be suppressed in the preferences and it also might not work if you have set $HistoryLength
to a low value, it should work with the default settings, though).
To read the expression, just set terms
to the return value of Get
, as this:
terms = Get[fname];
You might note that <<
and >>
are just shortcuts for Get
and Put
but will implicitly read the "argument" as a string (<< something
is actually equivalent to Get["something"]
). So you can't use the shortcuts with a filename stored in a variable as I did, which is a good reason to use the full function names and not the shortcuts...
Put
outputs to whatever directory is returned byDirectory[]
, which is by default your home directory $\endgroup$