I need a script to clear all ipynb outputs (recursive)
- User
I need a script to clear all ipynb outputs (recursive)
Assistant
Here's a Python script that recursively clears outputs from all Jupyter notebooks in a directory:
import os import json import nbformat def clear_notebook_outputs(notebook_path): """Clear all cell outputs in a Jupyter notebook.""" try: with open(notebook_path, 'r', encoding='utf-8') as f: notebook = nbformat.read(f, as_version=4) for cell in notebook.cells: if cell.cell_type == 'code': cell.outputs = [] cell.execution_count = None with open(notebook_path, 'w', encoding='utf-8') as f: nbformat.write(notebook, f) print(f"Cleared outputs in {notebook_path}") except Exception as e: print(f"Error processing {notebook_path}: {e}") def process_directory(directory): """Recursively process all .ipynb files in a directory.""" for root, dirs, files in os.walk(directory): for file in files: if file.endswith('.ipynb'): notebook_path = os.path.join(root, file) clear_notebook_outputs(notebook_path) if __name__ == "__main__": import sys if len(sys.argv) > 1: target_dir = sys.argv[1] else: target_dir = os.getcwd() print(f"Clearing outputs in all notebooks under: {target_dir}") process_directory(target_dir) print("Done!")Would you like me to explain or break down this code?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.