- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write a Python program to export a dataframe to an html file
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>
Advertisements