How to write to a CSV file in Python?

Published on Aug. 22, 2023, 12:17 p.m.

To write to a CSV file in Python, you can use the csv library or the pandas library. Here are two examples using both methods:

  1. Using the csv library:

import csv

with open(‘file.csv’, ‘w’, newline=’‘) as file:
writer = csv.writer(file)
writer.writerow([‘Column 1’, ‘Column 2’, ‘Column 3’]) # optional header row
writer.writerow([‘Value 1’, ‘Value 2’, ‘Value 3’])
writer.writerow([‘Value 4’, ‘Value 5’, ‘Value 6’])


2. Using the `pandas` library:

import pandas as pd

df = pd.DataFrame({‘Column 1’: [‘Value 1’, ‘Value 4’], ‘Column 2’: [‘Value 2’, ‘Value 5’], ‘Column 3’: [‘Value 3’, ‘Value 6’]})
df.to_csv(‘file.csv’, index=False)



Both methods involve opening the CSV file in a specified mode and writing data to it. The `csv` library provides fine-grained control over writing CSV files, while the `pandas` library provides a high-level interface to write out a `DataFrame` object to a CSV file with various formatting options.

Tags: