How to Write CSV Files in Pandas: Simple Guide
Use the
DataFrame.to_csv() method in pandas to write data to a CSV file. Specify the filename as a string, and optionally control options like delimiter, header, and index.Syntax
The basic syntax to write a DataFrame to a CSV file is:
DataFrame.to_csv(path_or_buf, sep=',', index=True, header=True)
Here, path_or_buf is the file name or path where the CSV will be saved.
sep sets the delimiter (default is comma).
index controls if row labels are saved (default is True).
header controls if column names are saved (default is True).
python
DataFrame.to_csv(path_or_buf, sep=',', index=True, header=True)
Example
This example creates a simple DataFrame and writes it to a CSV file named output.csv. It shows how the data is saved with default settings.
python
import pandas as pd data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]} df = pd.DataFrame(data) df.to_csv('output.csv') # To display the CSV content after writing (for demonstration): with open('output.csv', 'r') as file: print(file.read())
Output
Unnamed: 0,Name,Age
0,Alice,25
1,Bob,30
2,Charlie,35
Common Pitfalls
Some common mistakes when writing CSV files with pandas include:
- Forgetting to set
index=Falseif you don't want row numbers saved. - Not specifying the correct delimiter if your data uses a different separator.
- Overwriting important files without backup.
Always check the saved file to ensure it matches your expectations.
python
import pandas as pd data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]} df = pd.DataFrame(data) # Wrong: saves row index which may be unwanted df.to_csv('wrong.csv') # Right: avoid saving row index df.to_csv('right.csv', index=False) # Display contents for comparison with open('wrong.csv', 'r') as f: print('Wrong CSV content:\n' + f.read()) with open('right.csv', 'r') as f: print('Right CSV content:\n' + f.read())
Output
Wrong CSV content:
Unnamed: 0,Name,Age
0,Alice,25
1,Bob,30
Right CSV content:
Name,Age
Alice,25
Bob,30
Quick Reference
| Parameter | Description | Default |
|---|---|---|
| path_or_buf | File path or name to save CSV | Required |
| sep | Delimiter to use between fields | ',' |
| index | Write row names (index) or not | True |
| header | Write column names or not | True |
| mode | File mode (write or append) | 'w' |
| encoding | File encoding | utf-8 |
Key Takeaways
Use DataFrame.to_csv('filename.csv') to save data as CSV.
Set index=False to avoid saving row numbers if not needed.
Specify sep parameter to change delimiter if needed.
Check the saved file to confirm it matches your data format.
Be careful not to overwrite important files accidentally.