Is there a way to write printed out cells to a file easily?

NotebookFind[nb = EvaluationNotebook[], "Print", All, CellStyle];

This selects them but I would like to then write to a file.

  • 1
    $\begingroup$ Would it be possible for you to write them to a file when they're printed rather than after the fact? This would make it a lot easier, I think $\endgroup$ – user6014 Oct 29 '16 at 17:47
  • $\begingroup$ So for example, instead of Do[Print[x^2];, {x, 1, 10}], something like Do[Print[x^2]; Write[file, x^2];, {x, 1, 10}], which will print AND be writing the content to file as well. I don't know the scope of your project, but this could be easier and more efficient. $\endgroup$ – user6014 Oct 29 '16 at 18:45

The following approach does not write the selected cells directly to a file, rather it pastes them in a new notebook which is then saved as a file. (So this is not a clean method.) The notebook is created before the procedure and automatically closed without saving once finished.

temp = CreateDocument[{}, WindowSelected -> False]; 

NotebookFind[EvaluationNotebook[], "Print", All, CellStyle];
    FrontEndToken["Copy"], FrontEndToken[temp, "Paste"], 
    FrontEndToken[temp, "Save", {"C:/Users/Xavier/Desktop/file.txt", "Text"}]


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.