3

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.

0

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Holy cow that works! Clever thinking. Also, thanks for that Pandas link. It looks a bit involved, but I'll definitely study it, so I don't have to use (IMO) this kludgy way I'm doing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.