When trying to import some files into my Mathematica notebook, I wanted to use ToString
to specify the file path. Consider the following MWE, where we export some expression to the directory of the notebook, and immediately import it back:
In[1]:= Export[ToString[NotebookDirectory[]]<>"output.txt", 2020];
import1 = Import[ToString[NotebookDirectory[]]<>"output.txt"]
Out[2]= "2020"
This works as expected. However, consider using Get
and its symbolic representation <<
:
In[3]:= import2 = Get[ToString[NotebookDirectory[]]<>"output.txt"]
<< ToString[NotebookDirectory[]]<>"output.txt"
Out[3]= 2020
During evaluation of In[3]:= Get::noopen: Cannot open ToString[NotebookDirectory[]].
During evaluation of In[3]:= StringJoin::string: String expected at position 1 in $Failed<>output.txt.
Out[4]= $Failed <> "output.txt"
SoGet
works, but why does <<
make StringJoin
not recognise ToString[NotebookDirectory[]]
as a valid StringQ
? Am I using incorrect syntax?
Additional question: I also noticed that:
In[5]:= Head/@{import1, import2}
Out[5]= {String, Integer}
From the documentation, we read that Import
"imports data from the source, returning a Wolfram Language representation of it", contrary toGet
which also evaluates the expression. Does that mean the Import
ed data will always be of the String type, regardless of the type of data I export in the first step?
NotebookDirectory
already returns a string, so there is no need forToString
. 2. You may want to look atFileNameJoin
. 3. The results ofImport
depends on whether the input can be interpreted and translated to a MMA expression. In most (useful) cases, it will not be a string. See the docs. $\endgroup$ToString
; alsoFileNameJoin
is certainly useful. In either case though, the problem withGet
vs<<
persists. I can't understand why the latter does not recognise the file path (everything until "output.txt") as a valid sting. It would be interesting to find out the reason. $\endgroup$