0
$\begingroup$

I have a computer-generated plain text file with some Wolfram Language definitions separated by newline characters - imagine it is the code you would type to a single cell:

shape1 = Polygon{{0,1},{1,2},{-5,6}};

shape2 = Polygon{{0,-1},{5,-3},{5,9}};

I'd like to programmatically open this file in a notebook and evaluate the code so that shape1 and shape2 are accessible in this notebook. I tried different combinations of CreateDocument[], Import[] and EvaluateNotebook[] but nothing works the way I'd like to.

What should I do? It is possible to make some changes in this generated file, since it's done by a program of mine, but I would prefer not to.

$\endgroup$
  • $\begingroup$ The syntax in the file seems to be incorrect. It should read string = "shape1 = Polygon[{{0,1},{1,2},{-5,6}}]; shape2 = Polygon[{{0,-1},{5,-3},{5,9}}];". Having the correct string, ToExpression[string] works fine. Actually, Get[<<filename>>] should also work once the syntax has been corrected. $\endgroup$ – Henrik Schumacher Apr 1 '18 at 14:57
  • $\begingroup$ Actually this plain text file is saved with extension *.nb and opening it in Mathematica produces a correct notebook. I can for example click SHIFT+ENTER and get the contents evaluated correctly. $\endgroup$ – PKua Apr 1 '18 at 15:51
  • $\begingroup$ However doing ToExpression@Import["thefile.nb","Text"] did it's job, thanks. I would give +1 but I cannot yet. $\endgroup$ – PKua Apr 1 '18 at 15:58
2
$\begingroup$

Use Get["file.txt"] which reads in a file, evaluating each expression in it and returning the last one.

https://reference.wolfram.com/language/ref/Get.html

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.