0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Jupyter Notebookの.ipynbファイルをPythonスクリプトに変換する方法

Posted at

この記事は

私は普段サイエンティストとしてJupyter Notebook形式(.ipynb)のファイルをPythonスクリプト形式(.py)に変換することが多いのですが、
簡単に変換する方法に今更気づいたので共有します。

今回は/Users/test/Downloads/test.ipynbというパスにipynbファイルが存在するとします。

CLIでの変換

コマンドラインで簡単に変換する方法です。シンプルで素早く変換したい場合におすすめです。

jupyter nbconvert --to script /Users/test/Downloads/test.ipynb

このコマンドを実行すると、同じディレクトリにtest.pyというファイルが生成されます。

Pythonスクリプトでの変換

マークダウンの部分を除外したり、より細かい処理を入れたい場合はPythonスクリプトで変換します。柔軟にカスタマイズしたい場合に適しています。

import nbformat
from nbconvert import PythonExporter
from traitlets.config import Config
import os

# ConfigでMarkdownセルを除外
cfg = Config()
cfg.PythonExporter.exclude_markdown = True

# PythonExporter を生成
exporter = PythonExporter(config=cfg)

# 入力ファイルパス
input_path = '/Users/test/Downloads/test.ipynb'

# 出力ファイル名を入力ファイル名から生成
output_filename = os.path.splitext(os.path.basename(input_path))[0] + '.py'

# ノートブックを読み込んでスクリプト生成
nb = nbformat.read(input_path, as_version=4)
(script_body, resources) = exporter.from_notebook_node(nb)

# .py ファイルに書き込み
with open(output_filename, 'w') as f:
    f.write(script_body)

print(f"変換完了: {output_filename}が生成されました")

このスクリプトを実行すると、入力ファイル名に基づいた出力ファイル(この例ではtest.py)が生成されます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?