CSV Reader In Python With Example

Introduction to CSV Files

CSV stands for Comma Separated Values. CSV is a most popular and simple format of data representation.

Every day, large volumes of daily data like Stock Quotes, Weather updates and many other information is generated in the form of CSV.

CSV is often the most convenient form of storing and exchanging tabular data. Tabular data in a CSV file consists of several lines.

Each line in the CSV file is a record. A line in CSV file will have several fields separated by comma.

Several variations of CSV format exist - many of them varying in the delimiter and the new line character that separate the records. For example, instead of a Comma Character a CSV file may have its fields separated by tab or pipe symbol.

Processing of CSV Files

Every computer program of certain significance spends much of its time spending in input, preparing the input for the consumption of main program logic, preparing output for the consumption of other programs.

Writing a separate class or a program to deal with all the peculiarity of a format like CSV is a time consuming task. To ease the burden on the programmer from writing own CSV readers and CSV writers the Python Standard Library provides Reader, Writer and other related classes through the csv module.

Pyton CSV Module

The csv module pf The Python Standard Library provides Reader Objects and Writer Objects to process CSV data.

Python CSV Reader Example

import csv

 

with open('StockQuotes.csv', newline='') as QuoteFile:

    QuoteReader = csv.reader(QuoteFile, delimiter=',', quotechar='|')

 

    RowIndex = 1

    for row in QuoteReader:

        #Start printing a CSV record

        print("Quote %d:"%(RowIndex))

 

        RowIndex = RowIndex +1

       

        #Print Fields of a CSV record

        for field in row:

            print(field)

       

This example reads a CSV file containing stock quotes where the delimiter is a comma and no special end of line character is specified. The parameter to the python csv reader object is a fileobject representing the CSV file with the comma-separated fields as records.

The CSV reader object can be passed a file or any list supporting the python's iterator protocol. Stated simply, any python object that returns a string on calling __next__() method can be passed as a paramter to the CSV reader. The delimiter and the end of line characters are passed next.

Creation of the CSVReader reads all the lines in the CSV file. The CSV reader object is iterated and each CSV line or row is processed. Every row is returned by the CSVReader object as a list. Which is further printed as Row1 fields, Row2 fields and so on.

Python CSV Reader Output

Quote 1:

"GOOG"

 "794.02"

 "786.08"

 "794.48"

 "785.02"

 "552.95"

 "29.06"

 “-“

Quote 2:

“GOOG”

 "793.02"

 "786.08"

 "794.48"

 "785.02"

 "552.95"

 "29.06"

 “-“

 


Copyright 2023 © pythontic.com