This tutorial shows how to convert CSV file to Excel in Python with examples and detailed steps. The following shows the specific steps.
Steps of Convert CSV to Excel in Python
Step 1 Install Pandas
Pandas is a commonly used Python package and we can use it to convert CSV to Excel files. If your Python programming environment has not installed Pandas yet, you can do it as the first step.
# install Pandas into Python environment:
pip install pandas
Step 2 Read CSV into the Python environment
Next, you can read the CSV using Pandas function read_csv() to read the csv file. The following is the Python code example. I am using the CSV file from Github as example. You can read CSV files from your local computer as well.
# import the pandas package
import pandas as pd
# read csv files into the Python environment
sample_file = pd.read_csv ('https://raw.githubusercontent.com/TidyPython/Mediation_analysis/main/mediation_hypothetical_data.csv')
Step 3 Convert CSV files to Excel files
We can use to_excel() function to convert CSV files into Excel files in Python. The following is the sample Python code. Note that, it uses the file saved from Step 2, namely sample_file. In the code below, I also add code to check the corrent working directory, where the Excel file will be saved.
# Python code to save a CSV file to an Excel file
sample_file.to_excel ('sample_file.xlsx', index = None, header=True)
# import os package and print out the current working directory.
import os
os.getcwd()