11

I have a DateFrame 'tsod', now I convert it to html:

tsod.to_html()

How can I save this as a file? better save as a '.html' file.

wuwucat
  • 2,523
  • 8
  • 23
  • 26

3 Answers3

20
with open('my_file.html', 'w') as fo:
    fo.write(tsod.to_html())

or alternatively using pandas

tsod.to_html(open('my_file.html', 'w'))

or again (thanks @andy-hayden)

with open('my_file.html', 'w') as fo:
    tsod.to_html(fo)
danodonovan
  • 19,636
  • 10
  • 70
  • 78
  • 2
    I don't think `tsod.to_html('my_file.html')` will work. `to_html` doesn't accept a string, it accepts something it can write to, whether an open file or a StringIO buffer (it looks for `.write()`). You could use `tsod.to_html(fo)`, though. – DSM Feb 15 '13 at 15:42
  • Using StringIO is probably another way to solve this... write the html to a string, dump the string to a file. – tshauck Feb 15 '13 at 15:59
  • 1
    I think the good practice here is to still use with around the pandas bit: `tsod.to_html(fo)`. – Andy Hayden May 03 '13 at 18:10
  • Anyone that happens to find this now, `to_html` does take strings now so to name it just `tsod.to_html('Name.html')`. – Hercislife Apr 20 '21 at 19:20
5

As of the current version of pandas tsod.to_html('out.html') works fine.

Abbas
  • 3,872
  • 6
  • 36
  • 63
-1
a=tsod.to_html()
save(a,'path')

will work

wuwucat
  • 2,523
  • 8
  • 23
  • 26