0
0
Pandasdata~5 mins

Writing to CSV with to_csv in Pandas

Choose your learning style9 modes available
Introduction

Saving data to a CSV file lets you share or keep your data outside your program. CSV files are easy to open in many apps like Excel.

You want to save your cleaned data for later use.
You need to share data with someone who does not use Python.
You want to export results from your analysis to a spreadsheet.
You want to create a backup of your data after processing.
You want to move data between different programs or systems.
Syntax
Pandas
DataFrame.to_csv(path_or_buf=None, sep=',', index=True, header=True, encoding=None)

path_or_buf is the file path or object where the CSV will be saved.

index=True means row numbers are saved; set to False to skip them.

Examples
Saves the DataFrame df to a file named 'data.csv' with default settings.
Pandas
df.to_csv('data.csv')
Saves df without row numbers to 'data_no_index.csv'.
Pandas
df.to_csv('data_no_index.csv', index=False)
Saves df using tabs instead of commas as separators.
Pandas
df.to_csv('data_tab.csv', sep='\t')
Sample Program

This program creates a small table of names and ages, saves it to a CSV file without row numbers, then reads the file back and prints it to confirm the save worked.

Pandas
import pandas as pd

# Create a simple DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
df = pd.DataFrame(data)

# Save DataFrame to CSV without index
csv_file = 'people.csv'
df.to_csv(csv_file, index=False)

# Read back the CSV to check
loaded_df = pd.read_csv(csv_file)
print(loaded_df)
OutputSuccess
Important Notes

By default, to_csv saves the index (row numbers). Use index=False to avoid this.

You can change the separator with sep, for example to tab (\t).

Make sure you have write permission to the folder where you save the CSV file.

Summary

Use to_csv to save DataFrames as CSV files for easy sharing and storage.

Control whether row numbers are saved with the index parameter.

You can customize the separator and encoding if needed.