Friday, 20 June 2025

Transfer Jupyter Notebook into a text file

!pip install ipynbname
import json
import nbformat
from nbformat import read, write
import os
import ipynbname
def export_notebook_to_txt():
    # Get the current notebook name
    notebook_filename = ipynbname.name()
    
    # Get the full path to the notebook
    notebook_path = ipynbname.path()
    
    # Read the notebook
    with open(notebook_path, 'r', encoding='utf-8') as nb_file:
        notebook = read(nb_file, as_version=4)
    
    # Prepare content for TXT file
    notebook_content = []
    code_cell_count = 0
    for cell in notebook.cells:
        if cell.cell_type == 'code':
            code_cell_count += 1
            # cell_content = f'# [{code_cell_count}]\n'
            cell_content = cell.source
        elif cell.cell_type == 'markdown':
            cell_content = '# [MD]\n'
            cell_content += '# ' + cell.source.replace('\n', '\n# ')
        notebook_content.append(cell_content)
    # Join all cell contents
    full_content = '\n\n'.join(notebook_content)
    
    # Save to TXT file
    txt_filename = f'{notebook_filename.split(".")[0]}_content.txt'
    with open(txt_filename, 'w', encoding='utf-8') as txt_file:
        txt_file.write(full_content)
    return f"Notebook content has been exported to {txt_filename}"
# Run the function
export_notebook_to_txt()