Python provides CSV module to make it easy for us to write to a CSV file. In the previous tutorial on reading a CSV file using python that you can find here: Reading a CSV file we’ve seen how we can import a CSV and then read it using the reader method in the CSV module of python. In this tutorial we’ll see how we can write to a CSV file using the writer and the dictWriter functions provided by the python CSV module.
So let’s quickly go over CSV file again. CSV stands for comma separated values, so basically a CSV files have a bunch of values that are typically separated by commas, but there can be other separators too. Python helps up handle any kind of separator. In this example, we will learn how to:
Create and write a new CSV file
Write to an already existing CSV file
Append to an already existing CSV file
We will be using this as an already existing CSV file to write and append to:
Sample CSV file
CSV in Python Intro
So let’s get started with writing to CSV file using python, we’ll be going over the following things:
Import the CSV module
Open/Import the CSV file
Write to the CSV file using writer function
Write to the CSV file using dictWriter function
Python provides the CSV modules to handle CSV file. You can just read the file as a text file and use string comprehension to extract the required data if you just want to do it for the fun of it. But I recommend doing it using the CSV module so you can get the job done much quicker and in a cleaner way. So first of all we will import the CSV module in the top of our file like this.
Once we are done, we proceed to creating or opening a file for writing.
Opening the File to Write
Before you start writing to the CSV file, you need to know you use case. Is there a file that already exists and you need to add data to it, or do you want to overwrite the data in an already existing file, or does the file not exist and you will have to create it or do you want to write to the file only if it exists, else you don’t want to write to it.
There are different file open modes in python that you can take advantage of according to each use case. Let’s discuss those briefly:
– Append (a)
Use this mode when you want to open the file and add more data to the data that already exists in the file. This mode will create the file if it doesn’t already exists. You can use this mode like this:
– Write (a)
Use this mode if you don’t know if the file exists or not and you don’t care what data already exists in the file. Using this mode will replace all the data and just have the data that you’ve written to it. You use this mode like this:
– Check if a file exists
If you want to check if a file exists or not and take actions accordingly, use the isfile method like this:
import os.path os.path.isfile('example.csv')
Writing to CSV file Using writer
Now that we know how we can create or open the CSV file for writing, we’ll see how we can actually write the data to it. First off all, we will write the data using the writer method of the CSV module.
Here you can see, first we have a list of lists that define our data, each list inside the main list represents a row, for example let’s consider the first element:
['Delilah Traders', 43543, 25544678]
This define one vendor using name: Delilah Traders and Units sold is 43543 and the total revenue is 25544678, similarly each next list represents a new row in the CSV file. So now we have the data to be written, let examine the next line,
myFile = open('example.csv', 'w')
here we just open the file using the write mode, so that the file will be created if it doesn’t exist and all the data that already existed will be overwritten if the file already exists. Finally in the next group of lines we use the writer method of the CSV module so that we can write each list in the array of lists to the CSV, the following line:
writer = csv.writer(myFile)
Enables us to just write each list of data just using one line:
So now you now how to write a list of lists to the CSV file, but a lot time is real life, you might get the data from an API for from somewhere else in a dictionary format, in key-value pairs and then you need to appropriately insert values according to the respective keys. There’s certain benefit to this approach as we’ll see next.
Writing to CSV file Using DictWriter
DictWriter helps us to write content in dictionary format to a CSV file. To be honest, I’ve used dictWriter more than the normal writer as DictWriter fits most use cases and I don’t have to worry about the order of the items that I am trying to write to the CSV. Let’s see an example below.
Once we have opened or create the csv file for writing, we define the header fields i.e the column names in a list like this:
The items in this list define the column names, these are also the keys of the dictionary from which we will be inserting data into our CSV and as you’ve guessed by now, the value from a key will be inserted in the column with the same name as the key. Let’s take the dictionary below as an example:
This is it for this tutorial, I hope you know are equipped with the knowledge on how to write data to a CSV file using python. If you have any queries that you’d like to ask, feel free to drop them in the comment section below, I’ll try to help you to the best of my abilities.