Not sure chris has the right idea. I assume your file is not some exported data, strings, tables, etc. but rather a bunch of commands you basically want to execute from file, right? The Import
command tends to work with the types of files produced by Export
. It would probably treat your file as text.
You can use the Read
or ReadList
commands. If you use Read
it will step sequentially through each line of the text file executing each line. If you do ReadList
it will do them all at once. For example, I create a text file with the following contents:
Print["asdf"];
Plot[x,{x,1,10}];
Plot[x^2,{x,1,10}]
x=3;
Then when I do ReadList["C:\\test.txt"]
I will get the following:
(* Output:
asdf
{Null,Null,[Graphics Object Here],Null}
:End Output *)
The asdf comes from the Print
command, which is executed and does work. The list is all the output, which includes Null
for the lines ending with a semicolon. However, the graph of x^2
does show, because it does not have a semicolon.
Another way to do this might be:
While[Read["C:\\test.txt"] != "EndOfFile"]
which reads everything quietly -- no output because whatever output there is (be it Null
or something else), it will just be compared to "EndOfFile" and not returned. That includes the Print
command, which produces no output either.
After doing any one of these methods, if I ask for the value of x
I will get 3
as expected.
Edit: george2079 suggests changing the extension and opening the file with Mathematica. That too is possible, if all you want to do is turn a .txt file into a .nb file. I'm not sure that's what you want either, but if so, then that works.
tt = Import["~/test.txt"]
$\endgroup$