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.