如何从另一Jupyter Notebook批量运行nbstripout清理多文件夹Notebook
批量清理嵌套文件夹中的Jupyter Notebook(使用nbstripout)
前提准备
确保已安装nbstripout,如果未安装,在Jupyter Notebook中运行以下命令:
!pip install nbstripout
批量清理代码示例
直接在Jupyter Notebook中运行以下代码,替换根目录路径即可:
import os import subprocess # 替换为你的目标文件夹根路径 root_folder = "/your/target/folder/path" # 遍历所有嵌套文件夹 for current_dir, _, files in os.walk(root_folder): for file in files: if file.endswith(".ipynb"): full_path = os.path.join(current_dir, file) print(f"处理文件: {full_path}") # 调用nbstripout执行清理 try: subprocess.run( ["nbstripout", full_path], check=True, capture_output=True, text=True ) print(f"✅ 处理成功") except subprocess.CalledProcessError as err: print(f"❌ 处理失败,错误: {err.stderr.strip()}")
可选参数说明
- 若只想预览清理内容、不修改原文件,把命令改成
["nbstripout", "--dry-run", full_path] - 如需强制清理(忽略部分权限或文件状态问题),添加
--force参数:["nbstripout", "--force", full_path]
内容的提问来源于stack exchange,提问作者Kay
相关产品推荐
相关产品推荐

