把当前目录下所有ipynb文件里面的代码和md保存到txt文件

该文章已生成可运行项目,
import os
import json


def trans_ipynb_file_to_str(filename):
    # 读取 .ipynb 文件
    with open(filename, "r", encoding="utf-8") as f:
        notebook = json.load(f)

    # 提取所有单元格的文本内容
    all_text = []
    for cell in notebook["cells"]:
        if cell["cell_type"] == "code":
            strs = "".join(cell["source"])
            if strs != "":
                strs = "```python\n" + strs + "\n```\n\n"
                all_text.extend(strs)
        elif cell["cell_type"] == "markdown":
            strs = "".join(cell["source"]) + "\n"
            if strs != "":
                all_text.extend(strs)

    # 合并为字符串并复制到剪贴板
    text_to_copy = "".join(all_text)
    return text_to_copy


def save_to_txt():
    # 获取当前文件夹路径
    current_dir = os.getcwd()

    # 遍历当前文件夹下的所有文件
    for filename in os.listdir(current_dir):
        # 检查是否为 .ipynb 文件
        if filename.endswith(".ipynb"):
            
            # 构造对应的 .txt 文件名
            txt_filename = os.path.splitext(filename)[0] + ".txt"

            # 读取 .py 文件内容
            try:
                code_content = trans_ipynb_file_to_str(filename)

                # 写入到 .txt 文件
                with open(txt_filename, "w", encoding="utf-8") as txt_file:
                    txt_file.write(code_content)

                print(f"成功转换: {filename} -> {txt_filename}")

            except Exception as e:
                print(f"处理 {filename} 时出错: {e}")


if __name__ == "__main__":
    save_to_txt()
本文章已经生成可运行项目
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值