Writing CSV Files in Python

Posted by

In this article, we will learn to write CSV files using Python. CSV(Comma Separated Valued) file is a file format that stores the data in tabular form. In a CSV file, commas separate the fields and the file line contains the data record.

We will use the built-in module csv to work CSV files in Python. Here, we use the following two classes of this csv module to write CSV files:

  1. Writing files using the Python class csv.writer
  2. Writing files using the Python class csv.DictWriter

Writing files using the Python class csv.writer

It provides two methods( writerow() and writerows() ) to write CSV files. Method writerow() writes a single row at a time and writerows() writes multiple rows at a time.

We will follow the below steps for writing CSV files:

  1. Import csv module.
  2. Set headers and data.
  3. Open the CSV file in write mode.
  4. Create an object by calling the class writer of the module csv .
  5. Use writerow function for writing headers and using the function writerows() for writing data.

The example of the code for CSV writing:

You can check the python CSV file writing code using the module csv on GitHub also.

Writing files using the Python class csv.DictWriter

It is used to write dictionary-mapped data in the CSV file.

The following are steps for writing files using class csv.DictWriter

  1. Import csv module.
  2. Set headers and data in dictionary mapping.
  3. Open the CSV file in write mode.
  4. Create an object by calling the class DictWriter of the module csv .
  5. Use writeheader function for writing headers and use writerows() function for writing data.

An example of the code for writing CSV:

You can check Python CSV file writing using csv module and DictWriter method on GitHub

Leave a Reply

Your email address will not be published. Required fields are marked *