DEV Community

Tommi k Vincent
Tommi k Vincent

Posted on

Reading Data from CSV files using Reader objects in Python.

Definition of CSV files:A CSV (Comma Separated Values) format is one of the most simple and common ways to store tabular data.
For large CSV files, you’ll want to use the Reader object in a for loop. This avoids loading the entire file into memory at once. For example, create a file example.csv , then
enter the following code into it, as we want to read the it using CSV method from it.

4/5/2014 13:34,Mancity,73
4/5/2014 3:41,Arsenal,85
4/6/2014 12:46,Totethnam,14
4/8/2014 8:59,Chelsea,52
4/10/2014 2:07,Manchester-United,152
4/10/2014 18:10,Liverpool,23
4/10/2014 2:40,Leiceister-city,98

then run python3 to lunch interactive shell and type the following below code:

import csv

exampleFile = open('example.csv')
exampleReader = csv.reader(exampleFile)

for row in exampleReader:
print('Row #' + str(exampleReader.line_num) + '' + str(row))

exampleFile.close()



 output:
Row #1['4/5/2014 13:34', 'Mancity', '73']
Row #2['4/5/2014 3:41', 'Arsenal', '85']
Row #3['4/6/2014 12:46', 'Totethnam', '14']
Row #4['4/8/2014 8:59', 'Chelsea', '52']
Row #5['4/10/2014 2:07', 'Manchester-United', '152']
Row #6['4/10/2014 18:10', 'Liverpool', '23']
Row #7['4/10/2014 2:40', 'Leiceister-city', '98']

After you import the CSV module and make a Reader object from the CSV file, you can loop through the rows in the Reader object. Each row is a list of values, with each value representing a cell.The print() function call prints the number of the current row and the contents of the row. To get the row number, use the Reader object’s line_num
variable, which contains the number of the current line.
The Reader object can be looped over only once. To reread the CSV file, you must call csv. reader to create a Reader object.



Enter fullscreen mode Exit fullscreen mode

Top comments (0)