Export DataFrame to HTML File in Python



Assume, we have already saved pandas.csv file and export the file to Html format

Solution

To solve this, we will follow the steps given below −

  • Read the csv file using the read_csv method as follows −

df = pd.read_csv('pandas.csv')
  • Create new file pandas.html in write mode using file object,

f = open('pandas.html','w')
  • Declare result variable to convert dataframe to html file format,

result = df.to_html()
  • Using the file object, write all the data from the result. Finally close the file object,

f.write(result)
f.close()

Example

Let’s see the below implementation to get a better understanding −

import pandas as pd
df = pd.read_csv('pandas.csv')
print(df)
f = open('pandas.html','w')
result = df.to_html()
f.write(result)
f.close()

Output

pandas.html
<table border="1" class="dataframe">
   <thead>
      <tr style="text-align: right;">
         <th></th>
         <th>Id</th>
         <th>Data</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <th>0</th>
         <td>1</td>
         <td>11</td>
      </tr>
      <tr>
         <th>1</th>
         <td>2</td>
         <td>22</td>
      </tr>
      <tr>
         <th>2</th>
         <td>3</td>
         <td>33</td>
      </tr>
      <tr>
         <th>3</th>
         <td>4</td>
         <td>44</td>
      </tr>
      <tr>
         <th>4</th>
         <td>5</td>
         <td>55</td>
      </tr>
   </tbody>
</table>

Updated on: 2021-02-24T10:20:19+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements