# How to evaluate the same code in a whole bunch of existing notebooks

I have a large folder of existing notebooks, each currently containing a single cell of input. I would like --- in each of these notebooks --- to evaluate that cell, evaluate a new chunk of code I've written (whose purpose is to Export a text file and an image created from the data in the notebook), and re-save the notebook.

How can I do this in an automated way for the whole folder of files?

[Note: Each notebook has the same variables defined, but I have Notebook's Default Context set to Unique to This Notebook, so there should be no conflicts.]

• Can you explain in more detail what you want to achieve? Are you trying to modify those notebooks, add some text to them? Are you aware that kernel state is not local to notebooks? If you do a=1 in a notebook, then a==1 is True in all. Notebooks are just containers of text. – Szabolcs Dec 3 '14 at 16:37
• I have Notebook's Default Context set to Unique to This Notebook – thecommexokid Dec 3 '14 at 16:42
• The code I want to run in each notebook includes several Export statements. So I want to evaluate the existing code in the notebook (which is in a single cell), then run my new code (which exports an image and a text file). – thecommexokid Dec 3 '14 at 16:43
• Please edit these clarifications into the original question. – Szabolcs Dec 3 '14 at 16:44
• Have you tried working with NotebookEvaluate ? I'd suggest you take a stab at it and see what problems you run into. – george2079 Dec 3 '14 at 16:59

Rather simplistically, define a function to add the required cell to the end and evaluate a Notebook:

updateNotebook[file_] :=
Module[{nb = NotebookOpen[ToFileName[Directory[], file]]},
SelectionMove[nb, After, Notebook];
NotebookWrite[nb, Cell["Plot[Cos[y],{y,1,10}]", "Input"]];
NotebookEvaluate[nb, InsertResults -> True];
NotebookSave[nb];
NotebookClose[nb]; file]


Then map this function to a list of the Notebooks in your folder:

updateNotebook /@ FileNames["path/to/folder/*.nb"];


This is just an outline which should be improved with error checks, obviously replacing Plot[...] with the actual code you wish to add.

• Playing with this now, thanks. Is the only purpose of the final file to produce some visible evidence of having done something? – thecommexokid Dec 3 '14 at 19:44
• @thecommexokid, yes, I felt a list of Nulls wasn't too informative. – MikeLimaOscar Dec 4 '14 at 9:03
• I have it working great. One important modification I made was to add Visible -> False to the NotebookOpen command; otherwise it was seizure-inducing to watch! – thecommexokid Dec 6 '14 at 2:00