BruceWayne
BruceWayne

Reputation: 23283

How to send iPython HTML class to a .html file?

I have an object, class 'IPython.core.display.HTML, and I'm trying to save this as a .html file. How can I do that?

def HTML_with_style(df, style=None, random_id=None):
    # https://stackoverflow.com/questions/38511373/change-the-color-of-text-within-a-pandas-dataframe-html-table-python-using-style/38511805#38511805
    from IPython.display import HTML
    import numpy as np
    import re

    df_html = df.to_html()

    if random_id is None:
        random_id = 'id%d' % np.random.choice(np.arange(1000000))

    if style is None:
        style = """
        <style>
            table#{random_id} {{color: blue}}
        </style>
        """.format(random_id=random_id)
    else:
        new_style = []
        s = re.sub(r'</?style>', '', style).strip()
        for line in s.split('\n'):
                line = line.strip()
                if not re.match(r'^table', line):
                    line = re.sub(r'^', 'table ', line)
                new_style.append(line)
        new_style = ['<style>'] + new_style + ['</style>']

        style = re.sub(r'table(#\S+)?', 'table#%s' % random_id, '\n'.join(new_style))

    df_html = re.sub(r'<table', r'<table id=%s ' % random_id, df_html)

    return HTML(style + df_html)


new_df = HTML_with_style(df) # df is a Pandas DataFrame
f = open("test.html", 'w')
f.write(display(new_df))

But I get

TypeError: write() argument must be str, not None

Edit: Note, I'm not using IPython/Jupyter. I'm just trying to add some CSS to my HTML file, and found that HTML_with_style post. If this is the completely wrong way to go about this, please let me know.

Upvotes: 3

Views: 2124

Answers (1)

Haleemur Ali
Haleemur Ali

Reputation: 28313

it seems like you could replace

return HTML(style + df_html)

with

return style + df_html

and do the following:

with open('/path/to/file.html', 'w') as f:
    f.write(HTML_with_style(df))

But, maybe you should look into https://pandas.pydata.org/pandas-docs/stable/style.html for more complex styling.

I tested your function with my correction, saved a test dataframe & it shows up as a blue table in my browser like below as i believe it should:

enter image description here

Upvotes: 2

Related Questions