I want to delete in all notebooks in a certain root directory all output cells as well as all other output generated during evaluation (e.g. from print and other) and afterwards save the cleaned notebooks using the same names.

From here (Yves Klett) I borrowed some code:

CleanNotebook[nb_: SelectedNotebook[], 
   styles_: {"Output"}] := (NotebookFind[nb, #, All, CellStyle];
     NotebookDelete[nb];) & /@ styles;

ChoiceDialog[{FileNameSetter[Dynamic[imageDir], "Directory"], 
notebookFiles = FileNames["*.nb", imageDir, Infinity];
num = Length[notebookFiles];

  file = notebookFiles[[i]];
  nb = NotebookOpen[file, Visible -> False];
  NotebookSave[nb, file];
  , {i, 1, num}

My problem: Output cells seem to be correctly deleted BUT output from e.g. Print is not deleted. How can this be solved?


2 Answers 2


Print and Message and so on are generated cells, like the output from evaluating input. This, from the docs for Cells, is what you need (just substitute your actual notebook object for EvaluationNotebook[] in the code):

NotebookDelete[Cells[EvaluationNotebook[], GeneratedCell -> True]]

enter image description here

I'd use Map instead of Do but in any case just replace CleanNotebook[nb] with NotebookDelete[Cells[nb, GeneratedCell -> True]] in your code.

  • $\begingroup$ Perfect, thanks. $\endgroup$
    – mrz
    Commented Feb 26, 2018 at 7:30

Three additional alternatives:

  1. Call CleanNotebook with two arguments in your Do loop:

CleanNotebook[nb, {"Output", "Print"}];
  1. Replace the line CleanNotebook[nb]; in your Do loop with

  1. Replace your CleanNotebook with

cleanNotebook[nb_: SelectedNotebook[]] := SetOptions[nb, NotebookEventActions -> 
 {"WindowClose" :>  FrontEndExecute[FrontEndToken["DeleteGeneratedCells"]]}]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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