Notebook outputs can make an .ipynb file large, noisy in Git, or unsuitable to share when cells printed private data. nbconvert can strip saved outputs from the notebook JSON while leaving markdown and code cells in place.
The --clear-output flag is an in-place nbconvert mode. Work on a copied notebook when the original executed file should remain available for review, because the command overwrites the file named on the command line.
Clearing output also resets code cell execution_count values to null. It does not run cells, change source code, or remove markdown, so the cleaned notebook is ready for review, commits, or a fresh execution later.
Steps to clear notebook output with nbconvert:
- Create a working copy of the executed notebook.
$ cp analysis-demo.ipynb analysis-clean.ipynb
Skip the copy only when overwriting the original notebook is intended.
- Clear saved outputs from the copied notebook.
$ jupyter nbconvert --clear-output --inplace analysis-clean.ipynb [NbConvertApp] Converting notebook analysis-clean.ipynb to notebook [NbConvertApp] Writing 563 bytes to analysis-clean.ipynb
This command overwrites analysis-clean.ipynb. Keep the executed original until the cleaned copy has been checked.
- Verify that code outputs and execution counts were removed.
$ python - <<'PY' import json with open("analysis-clean.ipynb", encoding="utf-8") as f: nb = json.load(f) code_cells = [cell for cell in nb["cells"] if cell["cell_type"] == "code"] outputs = sum(len(cell.get("outputs", [])) for cell in code_cells) execution_counts = [cell.get("execution_count") for cell in code_cells] source = code_cells[0]["source"][0].strip() print(f"outputs after clear: {outputs}") print(f"execution counts after clear: {execution_counts}") print(f"first code cell source: {source}") PY outputs after clear: 0 execution counts after clear: [None] first code cell source: print('revenue:', 125000)
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.