Introduction

 CSV (Comma Separated Values) is a widely used file format for storing tabular data, and in Python, the process of writing data to CSV files is simple and straightforward. In this tutorial, you will learn how to write data to CSV files using Python programming language, and how to manipulate the data in various ways, such as sorting, filtering or joining it with other data sources.

Table of Contents :

  • Steps for Writing a CSV File
  • write a row to a CSV file
  • Writing multiple rows to CSV Files in Python
  • How to write to CSV Files using the DictWriter Class

Steps for Writing a CSV File

  • First, import the  csv  module.
  • Open a file using the  open()  function with the appropriate access type.
  • Create a  csv.writer()  object, passing the file object as a parameter.
  • Use the  writerow()  method of the  csv.writer()  object to write row(s) to the CSV file.
  • Close the file using the  close()  method.

write a row to a CSV file

  • The following example shows how to write a row to a CSV file.
  • Code Sample :

import csv

# Writing to a csv file
with open('data.csv', mode='w', newline='') as file:
   writer = csv.writer(file)
   writer.writerow(['Name', 'Age'])
   writer.writerow(['John', '26'])
   
   
   

Writing multiple rows to CSV Files in Python

  • We can write multiple rows to a CSV file by passing a list of lists to the  writerows()  method of the  csv.writer()   object.
  • Code Sample :


import csv

# Writing multiple rows to a csv file example
rows = [['Name', 'Age'], ['John', '26'], ['Jane', '24']]
with open('data.csv', mode='w', newline='') as file:
   writer = csv.writer(file)
   writer.writerows(rows)
   
   
   

How to write to CSV Files using the DictWriter Class

  • The  csv.DictWriter  class can be used to write rows to a CSV file as dictionaries.
  • First, create an object of the  csv.DictWriter  class, passing it the file object and field names.
  • Use the  writeheader()  method to write the header row to the CSV file.
  • Use the  writerows()  method to write rows to the CSV file as dictionaries.
  • Code Sample :

import csv

# Writing to a csv file as a dictionary
rows = [{'Name': 'John', 'Age': '26'}, {'Name': 'Jane', 'Age': '24'}]

with open('data.csv', mode='w', newline='') as file:
   fieldnames = ['Name', 'Age']
   writer = csv.DictWriter(file, fieldnames=fieldnames)
   writer.writeheader()  # Write header row
   writer.writerows(rows)  # Write rows
   
   
   

Prev. Tutorial : Reading csv files

Next Tutorial : References in Python