11

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"], 
   Dynamic[imageDir]}];
notebookFiles = FileNames["*.nb", imageDir, Infinity];
num = Length[notebookFiles];

Do[
  file = notebookFiles[[i]];
  nb = NotebookOpen[file, Visible -> False];
  CleanNotebook[nb];
  NotebookSave[nb, file];
  NotebookClose[nb];
  , {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?

mrz
  • 11,686
  • 2
  • 25
  • 81

2 Answers2

12

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.

Mike Honeychurch
  • 37,541
  • 3
  • 85
  • 158
6

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

FrontEndExecute[FrontEndToken["DeleteGeneratedCells"]];
  1. Replace your CleanNotebook with

cleanNotebook[nb_: SelectedNotebook[]] := SetOptions[nb, NotebookEventActions -> 
 {"WindowClose" :>  FrontEndExecute[FrontEndToken["DeleteGeneratedCells"]]}]
kglr
  • 394,356
  • 18
  • 477
  • 896