Convert CSV to Excel in Python Pandas – Python Pandas Tutorial

By | September 26, 2022

In this tutorial, we will use an example to show you how to convert a csv file to excel using python pandas.

Preliminary

In order to convert a csv to excel, we will use pd.read_csv() function to read a csv file.

A Beginner Guide to Python Pandas Read CSV – Python Pandas Tutorial

How to convert csv to excel using python pandas?

We can do as follows:

Step 1: read a csv file

Step 2: save csv data to excel file

Here we will use an example to show you how to convert.

import pandas as pd

def csv_to_xlsx_pd(csv_file, excel_file):
    csv = pd.read_csv(csv_file, sep = "\t", encoding='utf-8')
    print(csv)

    csv.to_excel(excel_file, sheet_name='data', index=None)

We should notice: the sep = “\t” in this example, you may change to yours, for example “,”

We can use this function as follows:

csv_file = "waimai_10k_test.csv"
excel_file = "waimai_10k_test.xlsx"

csv_to_xlsx_pd(csv_file, excel_file)

If you plan to convert several csv files in a foler, you can traverse them.

Python Traverse Files in a Directory for Beginners – Python Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *