-
Notifications
You must be signed in to change notification settings - Fork 1
/
clear-outputs.py
33 lines (26 loc) · 1.09 KB
/
clear-outputs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import os
import nbformat
from nbconvert.preprocessors import ClearOutputPreprocessor
def clear_notebook_outputs(notebook_path):
with open(notebook_path, 'r', encoding='utf-8') as f:
nb = nbformat.read(f, as_version=4)
# Create a preprocessor to clear outputs
preprocessor = ClearOutputPreprocessor()
# Process the notebook
cleared_nb, _ = preprocessor.preprocess(nb, {})
# Write the cleared notebook back to file
with open(notebook_path, 'w', encoding='utf-8') as f:
nbformat.write(cleared_nb, f)
def clear_all_notebooks_in_directory(directory):
for filename in os.listdir(directory):
if filename.endswith('.ipynb'):
notebook_path = os.path.join(directory, filename)
try:
clear_notebook_outputs(notebook_path)
print(f"Cleared outputs for {notebook_path}")
except Exception as e:
print(e)
print(f"Could not clear outputs for {notebook_path}")
if __name__ == "__main__":
directory_path = "./"
clear_all_notebooks_in_directory(directory_path)