Read and write CSV files in python

In this tutorial I'll show you how to parse a csv file in python and then how to generate a csv file.

First, we'll start with the csv file. Create a file users.csv with the following content:

user_1,,2018/11/20 10:12:24,200
user_2,,2018/11/20 16:45:58,100
user_3,,2018/11/21 14:37:35,40
user_4,,2018/11/21 13:53:16,400
user_5,,2018/11/22 17:35:38,600
user_6,,2018/11/22 19:22:10,300

Now, let's move our attention to the python script. Create a new file and add the following content

#!/usr/bin/env python

import csv

The parsed content from the csv file will be stored in a list.

Add the following line to the python script

rows = list()
# or the same can be achieved with the short notation
# rows = []

The next step is to read the csv file:

with open('users.csv') as file_content:
	csv_lines = csv.reader(file_content, delimiter=',', quotechar='"')
    for index, row in enumerate(csv_lines):
        # skip the first line
        if index == 0:

On the first line with open the csv file and use the with statement so that the file will be closed automatically even if the script encounter an error.

On the second line (inside the with statement) we create a variable csv_lines and we parse the csv file using comma , as delimiter and double quotes as quote character.

Next, we need to loop through every row and add it to our rows list. For this we'll use the enumerate keyword to have an index for every iteration. We do this to be able to skip the forst row, since it is the header declaration for the csv content.

Every row from the csv file will be appended to the rows list using append method.

Write csv data into a csv file

with open('my-csv-file.csv', 'wb') as csv_file:
    my_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

    for element in rows: