Comma separated values (CSV)

A common task in programming is working with CSV data. Writing is easy, just add a comma between the data on a row, but how do you read in a CSV file?

Method 1

Use the split function to break the string when it finds a comma.

data = []
with open("data.csv") as data_file:
    file_lines = data_file.read().splitlines()
    for line in file_lines:
        data.append(line.split(','))

Method 2

Import the csv module and use the reader method to go through each line.

import csv
data = []
with open("data.csv") as data_file:
    file_lines = csv.reader(data_file)
    for line in file_lines:
        data.append(line)

In the above examples you would end up with an array where each element contains an array representing a row of data from the file. So print(data[0][1]) would print the second column in the first row of the csv file.

Report a Glow concern
Cookie policy  Privacy policy