Getting Started

Python - IntroductionPython - Hello World ProgramPython - SyntaxPython - Data TypesPython - Variables

Operators

Python - Arithmetic OperatorsPython - Relational OperatorsPython - Logical OperatorsPython - Assignment OperatorsPython - Bitwise OperatorsPython - Membership OperatorsPython - Identity OperatorsPython - Increment and Decrement Operators

Conditions

Python - If Else statement

Loop

Python - While LoopPython - For Loop

Numbers

Python - NumbersPython - Number Conversion

Strings

Python - StringsPython - String OperatorsPython - String FormattingPython - String MethodsPython - String Format Method

List

Python - ListPython - List Methods

Tuple

Python - Tuple

Set

Python - SetPython - Set Methods

Dictionary

Python - DictionaryPython - Dictionary Methods

Functions

Python - FunctionsPython - Functions - Variable length argumentsPython - Lambda Function

Scope of Variables

Python - Scope of Variables

Modules

Python - ModulesPython - Math ModulePython - JSON ModulePython - datetime ModulePython - time Module

I/O

Python - Read input from keyboard

File

Python - File Handling

Exception Handling

Python - Exception Handling

OOP

Python - Classes and ObjectsPython - Class Constructor __init__ methodPython - Class Destructor __del__ methodPython - Built-in Class AttributesPython - InheritancePython - Method OverridingPython - Method Overloading

Package Management

Python - PIP

Python - MySQL

Python - MySQL - Getting StartedPython - MySQL - Insert dataPython - MySQL - Select dataPython - MySQL - Update dataPython - MySQL - Delete data

Python - CSV

Python - Read data from CSV filePython - Write data in CSV file

Python - Read data from CSV file

Python

python logo

In this tutorial we will learn to read CSV file in Python.

What is a CSV file?

A CSV or Comma Separated Values is a plain text file containing tabular data in printable ASCII or Unicode characters.

Points to note!

CSV files are saved with .csv extension.

You can create CSV files using text editors like Notepad, Sublime Text etc.

You can also use application like MS-Excel to create CSV files.

Sample CSV file

In the following example we have the content of a sample CSV file containing 4 rows and 3 columns.

id,name,score
1,Jane Doe,10
2,John Doe,9
3,Alice,10

The first row of the file is generally the name of the columns.

The above file has 3 columns - id, name and score. The remaining three rows contain the data.

Import the csv module

To work with CSV files in Python we take help of the csv module.

Import the csv module by writing the following line.

import csv

Reading CSV file

To read CSV file data we take help of the reader() method of the csv module.

In the following Python program we are reading the content of the data.csv file and printing its content in the console.

Content of the data.csv file.

id,name,score
1,Jane Doe,10
2,John Doe,9
3,Alice,10

Python code to read CSV file.

# import module
import csv

try:
    # open file
    fobj = open('data.csv', 'r')
    
    # reader object
    csvReader = csv.reader(fobj)
    
    # get the field name
    fields = csvReader.next()
    
    # total columns
    columnsCount = len(fields)
    
    # iterate the rows
    rows = []
    for row in csvReader:
        rows.append(row)
    
    # print rows
    for r in rows:
        for i in range(columnsCount):
            print(fields[i] + " = " + r[i])
        print("------")
    
except:
    print("An error occurred while reading the file.")

finally:
    fobj.close()

The above Python code will give us the following output.

id = 1
name = Jane Doe
score = 10
------
id = 2
name = John Doe
score = 9
------
id = 3
name = Alice
score = 10
------

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT