[Python] Create a Python file that would run Jupyter Notebook in loop and save results to HTML

Discussão em 'Python' iniciado por Stack, Fevereiro 15, 2025.

  1. Stack

    Stack Membro Participativo

    Currently I have a jupyter notebook data analysis that I run for multiple countries and the only thing I need to do is replace the "country" variable on top with the country I desire to run the analysis. After analysis is complete, I have to save the jupyter and only then run this code:

    !jupyter nbconvert DataAnalysis.ipynb --no-input --no-prompt --to html


    This would generate an HTML file I have to rename, then change the "country" variable again for another country, run the script (besides last line that is commented out), save the result after graphs are displayed, and run the last line again and so on.

    I want to create a Python file that would execute this Jupyter and save the reports (with any name, just identifying which country it is) in a "Reports" folder in loop, tried this with help of chatgpt but have no idea what to do:

    import os

    # List of countries for which reports are needed
    countries = ['Czech Queue','Switzerland Queue','Netherlands Queue','Portugal Queue','Peru Queue','London Queue','Sweden Queue','Slovakia Queue','Finland Queue','Denmark Queue','Norway Queue','Spain Queue','France Queue']

    notebook_input = "DataAnalysis.ipynb" # Your original notebook
    output_dir = "Reports"
    os.makedirs(output_dir, exist_ok=True)

    for country in countries:
    output_notebook = os.path.join(output_dir, f"{country.replace(' ', '_')}_Report.ipynb")
    output_html = os.path.join(output_dir, f"{country.replace(' ', '_')}_Report.html")

    print(f"Generating report for {country}...")

    # Read the notebook content
    with open(notebook_input, "r", encoding="utf-8") as f:
    notebook_content = f.read()

    # Replace any existing "country =" assignment to the correct country
    notebook_content = notebook_content.replace('country = ', f'country = "{country}" #')

    # Write the updated notebook
    with open(output_notebook, "w", encoding="utf-8") as f:
    f.write(notebook_content)

    # Execute the notebook in place
    os.system(f"jupyter nbconvert --execute --inplace {output_notebook}")

    # Convert executed notebook to HTML
    os.system(f"jupyter nbconvert {output_notebook} --no-input --no-prompt --to html --output {output_html}")

    print("All reports generated successfully!")


    Any idea on how this could be achievable?

    Continue reading...

Compartilhe esta Página