将 .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_file
和 ipynb_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
文件。下面是一个示例脚本:
- 确保你已经安装了
nbformat
库:
pip install nbformat
- 创建一个 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)
-
将
directory
变量替换为你要转换的.py
文件所在的目录路径。 -
运行脚本:
python convert_py_to_ipynb.py
这个脚本将会遍历指定目录下的所有 .py
文件,并将它们转换为 .ipynb
文件,保存在相同的目录中。
另一个简单方法
在jupyter notebook单元格中运行如下代码
%load xxx.py