Read 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:

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

Now, let's move our attention to the python script. Create a new file parser.py 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:
            continue
            
        rows.append(row)

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.