Skip to content

Instantly share code, notes, and snippets.

@Ma5onic
Created March 3, 2023 16:12
Show Gist options
  • Save Ma5onic/1490a723e8c4a79d1b2c197c85c8cdaa to your computer and use it in GitHub Desktop.
Save Ma5onic/1490a723e8c4a79d1b2c197c85c8cdaa to your computer and use it in GitHub Desktop.
Simple Python script that converts Python notebook files (.ipynb) to Python scripts (.py)
import os
import sys
import json
def ipynb_to_py(ipynb_file_path):
# Open the ipynb file and load its contents as JSON
with open(ipynb_file_path, 'r') as f:
nb = json.load(f)
# Create a new .py file with the same name as the ipynb file
py_file_path = os.path.splitext(ipynb_file_path)[0] + '.py'
with open(py_file_path, 'w') as f:
# Loop through each cell in the notebook
for cell in nb['cells']:
# If the cell contains code, write it to the .py file
if cell['cell_type'] == 'code':
code_lines = cell['source']
code = ''.join(code_lines)
f.write(code + '\n')
print(f'{ipynb_file_path} converted to {py_file_path}')
if __name__ == '__main__':
if len(sys.argv) != 2:
print('Usage: python ipynb_to_py.py <ipynb_file>')
else:
ipynb_file = sys.argv[1]
ipynb_to_py(ipynb_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment