将py文件转为ipynb文件(含批量转换方法)

.py 文件转换为 .ipynb 文件(Jupyter Notebook),有几种方法可以实现。下面是使用 nbformat 库的一个示例。

首先,确保你已经安装了 nbformat 库:

pip install nbformat

单文件转换

使用下面的 Python 脚本将 .py 文件转换为 .ipynb 文件:

import nbformat as nbf

def py_to_ipynb(py_file, ipynb_file):
    with open(py_file, 'r', encoding='utf-8') as f:
        code = f.read()

    # 创建一个新的 Notebook
    nb = nbf.v4.new_notebook()

    # 将代码分成单独的代码单元格
    cells = []
    for cell in code.split('\n\n'):
        cells.append(nbf.v4.new_code_cell(cell))

    nb['cells'] = cells

    # 保存为 .ipynb 文件
    with open(ipynb_file, 'w', encoding='utf-8') as f:
        nbf.write(nb, f)

# 使用示例
py_file = '你的脚本.py'
ipynb_file = '你的脚本.ipynb'
py_to_ipynb(py_file, ipynb_file)

这个脚本将 .py 文件的内容读取并分割成多个代码单元格,然后将这些单元格写入到新的 .ipynb 文件中。请根据需要修改 py_fileipynb_file 的路径。

如果你希望在 Jupyter Notebook 环境中完成这个转换,也可以使用类似的方法:

import nbformat as nbf

# 读取 .py 文件内容
py_file = '你的脚本.py'
with open(py_file, 'r', encoding='utf-8') as f:
    code = f.read()

# 创建一个新的 Notebook
nb = nbf.v4.new_notebook()

# 将代码分成单独的代码单元格
cells = []
for cell in code.split('\n\n'):
    cells.append(nbf.v4.new_code_cell(cell))

nb['cells'] = cells

# 保存为 .ipynb 文件
ipynb_file = '你的脚本.ipynb'
with open(ipynb_file, 'w', encoding='utf-8') as f:
    nbf.write(nb, f)

通过以上方法,你可以轻松地将 .py 文件转换为 .ipynb 文件,并在 Jupyter Notebook 中使用。

批量转换

你可以编写一个 Python 脚本,遍历指定目录下的所有 .py 文件,并将它们转换为 .ipynb 文件。下面是一个示例脚本:

  1. 确保你已经安装了 nbformat 库:
pip install nbformat
  1. 创建一个 Python 脚本 convert_py_to_ipynb.py,并将以下代码粘贴到其中:
import nbformat as nbf
import os

def py_to_ipynb(py_file, ipynb_file):
    with open(py_file, 'r', encoding='utf-8') as f:
        code = f.read()

    # 创建一个新的 Notebook
    nb = nbf.v4.new_notebook()

    # 将代码分成单独的代码单元格
    cells = []
    for cell in code.split('\n\n'):
        cells.append(nbf.v4.new_code_cell(cell))

    nb['cells'] = cells

    # 保存为 .ipynb 文件
    with open(ipynb_file, 'w', encoding='utf-8') as f:
        nbf.write(nb, f)

def convert_directory(directory):
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith(".py"):
                py_file = os.path.join(root, file)
                ipynb_file = os.path.splitext(py_file)[0] + '.ipynb'
                print(f"Converting {py_file} to {ipynb_file}")
                py_to_ipynb(py_file, ipynb_file)

# 使用示例
directory = '你的目录路径'  # 替换为你的目录路径
convert_directory(directory)
  1. directory 变量替换为你要转换的 .py 文件所在的目录路径。

  2. 运行脚本:

python convert_py_to_ipynb.py

这个脚本将会遍历指定目录下的所有 .py 文件,并将它们转换为 .ipynb 文件,保存在相同的目录中。

另一个简单方法

在jupyter notebook单元格中运行如下代码

%load xxx.py
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值