Reputation: 25659
Answering questions Stack Overflow, I use the same ipython notebook, which makes its easier to search previously given answers.
The notebook is starting to slow down. The question I have is: How do I count the numbers of cells in the notebook?
Upvotes: 4
Views: 4955
Reputation: 7163
python -c "import sys, json; print(len(json.load(open(sys.argv[1],'r'))['cells']))" <notebook_filename.ipynb>
One-liner based on https://stackoverflow.com/a/38925464/588437.
Upvotes: 0
Reputation: 2238
There's actually no need to parse the json. Just read it as text and count instances of, for example, "cell type":
with open(fname, 'r') as f:
counter = 0
for line in f:
if '"cell_type":' in line:
counter += 1
Or, even easier, just open your .ipynb notebook in a text editor, then highlight the same bit of text and see the count by hitting ctrl+F (or whatever the binding is for search).
If any cells have markdown and you want to avoid those, you can just search on "cell_type": "code",
too.
Although as others have said, you're better off not storing your code this way. Or at least, I imagine you can store it in ways that will make it much easier to access in the future, if you want it for reference.
Upvotes: 5
Reputation: 29711
You could execute your notebook from the command line by:
jupyter nbconvert --ExecutePreprocessor.allow_errors=True --to notebook --execute jupyter_notebook.ipynb
where: jupyter_notebook.ipynb
should be replaced with your filename.ipynb
.
With allow_errors=True
, the notebook is executed until the end, regardless of any error encountered during the execution. The output notebook, will contain the stack-traces and error messages for all the cells raising exceptions.
Upvotes: 2
Reputation: 12039
For example:
import json
document = json.load(open(filepath,'r'))
for worksheet in document['worksheets']:
print len(worksheet['cells'])
Upvotes: 6