How to Write a CSV File in Python

Writing data to a CSV (Comma-Separated Values) file is a common task for many applications. CSV files help store tabular data in a simple text format, and they are widely used for data exchange between applications and systems. In this tutorial, we will walk through the steps of how to write CSV files using Python.

Python features a powerful standard library for handling CSV files called csv. With the csv library, you can easily read from and write to CSV files with just a few lines of code.

Steps

Step 1: Importing the CSV Module

To work with CSV files in Python, you’ll need to import the built-in csv module. This module provides the necessary functionalities to write to and read from CSV files.

Step 2: Prepare Your Data

Before writing to a CSV file, you must have your data ready. Typically, your data should be organized in a list of rows, with each row being a list of values corresponding to columns. Here’s a simple example of how data might be structured:

Step 3: Writing to a CSV File

You need to open a file in write mode and then use the csv.writer object to write the data. You can use the .writerow() method for writing a single row, and the .writerows() method for writing multiple rows at once.

In the example above, we open a file named people.csv in write mode ('w'). The newline='' parameter is used to prevent blank lines from being added between rows on Windows. We then create a csv.writer object and use it to first write the headers and then all the rows of data.

Step 4: Adding Custom Formatting

The csv.writer also allows you to customize the formatting of your CSV file using the Dialect and Formatting Parameters. For example, you may want to change the delimiter from a comma to a tab or include a quote character around each data item.

This code writes the data to a TSV (Tab-Separated Values) file, using tabs instead of commas to separate fields. It also wraps each data item in quotes.

Step 5: Using DictWriter When Working with Dictionaries

If you prefer to work with dictionaries that map column names to their respective values, you can use the csv.DictWriter class. The following example demonstrates this approach:

With DictWriter, you specify the column names when creating the writer object. You must call the .writeheader() method to write the header row, and then you can write rows using dictionaries that map headers to their values.

Full Example Code

Here is the complete code for writing a CSV file using the csv module in Python:

Result

Conclusion

In this tutorial, we’ve learned how to use Python’s built-in csv module to write data to a CSV file. You’ve seen how to prepare your data, write data using both csv.writer and csv.DictWriter, and customize the format of your CSV file. With this knowledge, you can now easily create and manipulate CSV files to store and share data.