Reading and Writing CSV Files

What is a csv file ?

A CSV is a comma separated values file which allows data to be saved in a table structured format. All CSV files are plain text , can contain numbers and letters only, and structure the data contained within them in a tabular, or table, form.

Sample CSV File Data

column1,column2,column3,column4 data11,data12,data13,data14 data21,data22,data23,data24 data31,data32,data33,data34 data41,data42,data43,data44
The csv module in Python implements classes to operate with CSV files. There are two ways to read a CSV file. You can use the csv module's reader function or you can use the DictReader class.

Usig csv.reader

The csv.reader() method can be used to extract data from a file that contains CSV-formatted data. This method returns a reader object, which can be iterated over to retrieve the lines of your CSV and the data is read as a list of strings. example
import csv with open('data.csv') as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: print(row)

Every row is returned as an array and can be accessed as such, to print the first cells we could simply write: row[0], row[1], row[2] etc.

import csv with open('data.csv') as csvfile: reader = csv.reader(csvfile, delimiter=',') for col in reader: print(col[0], " : ",col[1], " : ", col[2], " : ", col[3])
output
column1 : column2 : column3 : column4 data11 : data12 : data13 : data14 data21 : data22 : data23 : data24 data31 : data32 : data33 : data34 data41 : data42 : data43 : data44

Using DictReader class

Python's DictReader class basically creates a CSV object that behaves like a Python OrderedDict . It works by reading in the first line of the CSV and using each comma separated value in this line as a dictionary key. The columns in each subsequent row then behave like dictionary values and can be accessed with the appropriate key. example
import csv with open('data.csv') as csvfile: reader = csv.DictReader(csvfile, delimiter=',') for line in reader: print(line["column1"], line["column2"],line["column3"],line["column4"])
output
data11 data12 data13 data14 data21 data22 data23 data24 data31 data32 data33 data34 data41 data42 data43 data44

Writing to CSV Files

The csv module also has two methods that you can use to write a CSV file. You can use the writer function or the DictWriter class. The writer object presents two functions, namely writerow() and writerows() . The difference between them, as you can probably tell from the names, is that the first function will only write one row, and the function writerows() writes several rows at once. example
import csv data = [['column1','column2'],['data11','data12'],['data21','data22']] csv_file = open('data1.csv', 'w') with csv_file: writer = csv.writer(csv_file) writer.writerows(data) print("Done")