How to Save Dataframes as CSV and xlsx Files in Python

This tutorial demonstrates how to save a dataframe as CSV and xlsx files in Python.

Part 1: CSV Files

We can first write a dictionary, then transform it into a dataframe. After that, we can use to_csv() save it as a CSV.

import pandas as pd

d = {'brands': ['Tesla', 'Toyota'], 'models': ["Model 3", "RAV4"]}
df = pd.DataFrame(data=d)
print(df)

df.to_csv("Car_brands.csv")
   brands   models
0   Tesla  Model 3
1  Toyota     RAV4

The CSV file is saved into your current folder as well.

CSV file of Car Models

Part 2: xlsx Files

We can use to_excel() to save a dataframe as a xlsx file. The following code shows you how to save a dataframe as a xlsx file in Python.

import pandas as pd

d = {'brands': ['Tesla', 'Toyota'], 'models': ["Model 3", "RAV4"]}
df = pd.DataFrame(data=d)

df.to_excel("Car_brands.xlsx", sheet_name='sheet1', index=False)

The following is the screenshot of how it looks like as a xlsx file.

Python write as a xlsx file

Other Resources