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()
把当前目录下所有ipynb文件里面的代码和md保存到txt文件
于 2025-05-11 10:11:20 首次发布
该文章已生成可运行项目,
本文章已经生成可运行项目
954

被折叠的 条评论
为什么被折叠?



