Sub topic 2
Saving a DataFrame to CSV
This chapter assumes you can run Python scripts or notebooks, build and inspect a pandas DataFrame, install packages with pip, and recognize column dtypes such as int, float, string, and datetime. You need only pandas for CSV. Excel and Parquet need extra libraries, which later chapters cover.
By the end you will be able to write a DataFrame to a CSV file with to_csv. You will also know what the default output looks like, why the index column causes trouble, and how to write to a file, a buffer, or a string.
What a CSV file is
CSV stands for comma-separated values. It is a plain text file where each line is one row and a separator character splits the fields on that line. The first line usually holds the column names.
CSV has no schema. The file does not record whether a column is an integer, a date, or text. Every value is stored as characters, and the program that reads the file has to guess the types again. The chapter on round trips covers what this costs you. For now, remember that CSV is easy to open anywhere and carries no type information.
The basic call
Start with a small DataFrame that has text, missing values, floats, and dates.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 3],
"customer": ["Ana", "Ben", None],
"amount": [19.99, 5.5, None],
"ordered_at": pd.to_datetime(["2026-01-05", "2026-01-06", "2026-01-07"]),
})
df.to_csv("orders.csv", index=False)The first argument is the destination. A string or pathlib.Path is treated as a file path. The file is created if it does not exist and overwritten if it does, so a second run replaces the first result without warning.
The file now contains this text:
order_id,customer,amount,ordered_at
1,Ana,19.99,2026-01-05
2,Ben,5.5,2026-01-06
3,,,2026-01-07Four defaults are visible here:
- The header line holds the column names.
- Missing values (
NoneandNaN) become empty fields, so row 3 shows,,. - Floats are written with as many digits as needed.
5.5stays5.5and does not become5.50. - Datetimes are written in ISO format. When every value in the column is at midnight, only the date part is written.
The index trap
By default to_csv also writes the DataFrame's index as the first column. Here is what happens if you leave index=False out.
print(df.to_csv())The output starts like this:
,order_id,customer,amount,ordered_at
0,1,Ana,19.99,2026-01-05
1,2,Ben,5.5,2026-01-06
2,3,,,2026-01-07The first header cell is empty because the default index has no name. When someone reads this file with pd.read_csv, that column comes back as Unnamed: 0. Many pipelines carry that stray column for months before anyone notices.
Use index=False when the index is just a row counter. Keep the index when it carries meaning, such as a customer ID or a timestamp. In that case give it a name and tell read_csv which column to use:
indexed = df.set_index("order_id")
indexed.to_csv("orders_indexed.csv")
back = pd.read_csv("orders_indexed.csv", index_col="order_id")Here the index already has the name order_id, so the header is correct. If your index is unnamed, pass index_label="some_name" to to_csv to name it in the header.
Where the output can go
The first argument of to_csv does not have to be a file path. It accepts three kinds of destination.
| Destination | Example | Result |
|---|---|---|
| File path | `df.to_csv("out.csv")` | Writes the file and returns `None` |
| File-like object | `df.to_csv(buffer)` | Writes into an open file or an `io.StringIO` buffer, returns `None` |
| Nothing | `df.to_csv()` | Returns the CSV text as a string |
The string form is useful for quick checks, for tests, and for sending CSV text over a network without touching the disk. A buffer is useful when another library expects a file object.
import io
buffer = io.StringIO()
df.to_csv(buffer, index=False)
text = buffer.getvalue()
print(text.splitlines()[0])This prints the header line, order_id,customer,amount,ordered_at.
If you open a file yourself and pass the handle, open it with newline="". The csv machinery handles line endings itself, and without this setting you can get blank lines between rows on Windows.
with open("orders_handle.csv", "w", newline="", encoding="utf-8") as f:
df.to_csv(f, index=False)Choosing columns and write mode
The columns argument selects and orders the columns to write, without changing the DataFrame:
df.to_csv("orders_slim.csv", columns=["order_id", "amount"], index=False)The mode argument controls how the file is opened. The default is "w", which overwrites. Mode "a" appends to the end of an existing file, which matters for chunked writing later in this tutorial. Mode "x" raises FileExistsError if the file is already there, which protects you from overwriting a result by accident:
df.to_csv("orders_once.csv", index=False, mode="x")Running this line twice fails on the second run. That is the behavior you want when a file must never be replaced.
Quoting happens automatically
A field that contains the separator, a double quote, or a line break would break the file structure if written as is. By default pandas wraps such fields in double quotes and doubles any quote characters inside them.
notes = pd.DataFrame({
"id": [1, 2],
"note": ["Deliver to Dock 4, rear", 'Said "call first"'],
})
print(notes.to_csv(index=False))The output is:
id,note
1,"Deliver to Dock 4, rear"
2,"Said ""call first"""Any correct CSV reader, including pd.read_csv, undoes this quoting. You rarely need to change it, but it explains why a CSV file with free text can look strange to the eye and still be valid. You can change the behavior with the quoting argument, using constants from the standard csv module.
How the call flows
The next diagram shows the path from DataFrame to destination.
The conversion step is where type information disappears. After it, every cell is characters.
Common errors
These problems appear often when people first save CSV files.
- An
Unnamed: 0column after reading the file back. The index was written and then read as data. Write withindex=False, or read withindex_col=0. - A silently overwritten file. The default mode replaces the file. Use
mode="x"or check withpathlib.Path.exists()when that matters. FileNotFoundErrororOSErrorfor the path.to_csvcreates the file, not the folders above it. Create the folder first, for example withPath("out").mkdir(exist_ok=True).- A
PermissionErroron Windows. The target file is open in Excel, which locks it. Close it and run the script again. - Blank lines between rows. You passed a handle opened without
newline="". - Missing values that look like zero or text. The default writes an empty field, and some readers cannot tell an empty field from an empty string. The next chapter shows
na_repfor an explicit marker.
A practical checklist
Before you rely on a CSV file, run through these checks:
- Write with
index=Falseunless the index has meaning. - Open the file in a text editor, or print the first lines, to see what was written.
- Confirm that the destination folder exists and that you want to overwrite any earlier file.
- Read the file back and compare it with the original, as the verification chapter shows.
Exercise
You run df.to_csv("result.csv") on a DataFrame with the default integer index. A colleague reads the file with pd.read_csv("result.csv") and finds an extra column named Unnamed: 0. Why does this happen, and give two ways to fix it?
Show answer
to_csv writes the index as the first column by default, and that column has no header name because the index is unnamed. read_csv then treats it as ordinary data and labels it Unnamed: 0. Fix it either by writing the file with df.to_csv("result.csv", index=False), or by reading it with pd.read_csv("result.csv", index_col=0) so the first column becomes the index again.
Exercise
Which call returns the CSV content as a string without creating any file, and which mode value makes to_csv raise an error when the target file already exists?
Show answer
df.to_csv() with no path argument returns the CSV text as a string. mode="x" raises FileExistsError if the file already exists.