How To Convert Multiple CSV Files To Excel In Python

In this tutorial, we will learn how to convert multiple CSV files to Excel files using Python. Converting CSV files to Excel files can be a useful feature when you need to organize data in a more readable format. For this tutorial, we will use pandas and openpyxl libraries to achieve this conversion.

If you don’t have these libraries installed, you can do it using pip:

Let’s assume we have three CSV files named file1.csv, file2.csv, and file3.csv. Our goal is to convert them into three separate Excel files.

Step 1: Import relevant libraries

First, we need to import the required libraries – pandas and os (for file handling):

Step 2: Get a list of CSV files in the input folder

To get a list of all the CSV files in the input folder, we can use the os.listdir() function with a filtering condition:

Expected output listing the CSV files:

['file1.csv', 'file2.csv', 'file3.csv']

Step 3: Convert each CSV file to an Excel file

We will loop through the list of the CSV files, use pandas to load each file, and then save it as an Excel file with the to_excel() pandas function:

Note: We will use the os.path.splitext() function to extract the file name without extension, which will be used to name the Excel file:

After running this code block, you will find Excel files (file1.xlsx, file2.xlsx, and file3.xlsx) converted from the CSV files in the specified output folder.

Full code

Here is the complete code to convert multiple CSV files to Excel files:

Conclusion

In this tutorial, we have learned how to use Python to convert multiple CSV files to Excel files using pandas and openpyxl. This process can be very helpful in organizing and presenting data in a more user-friendly format.