Reading CSV files in Python

Posted by

In this tutorial, we will learn for reading CSV files in Python. The file format known as CSV (Comma Separated Values) holds data in tabular form. The fields are separated by commas in a CSV file, and the file line includes the data record.

There are basically two common methods of reading a CSV file in Python. First is module csv , and the second is the Pandas library.

Using csv module and reader class

It is a common module for reading or writing CSV files in Python. Here are the steps, we will follow to read a CSV File:

  1. Import csv module.
  2. Open the CSV file in read mode.
  3. Create an object by calling the class reader of the module csv . Reader class reads the file line by line and returns the object.
  4. Run a loop for showing the data.

Using csv module and DictReader class

DistReader class maps the first line of data as keys and returns data in the dictionary format.

Steps for reading a CSV file using class DictReader :

  1. Import csv module.
  2. Open the CSV file in read mode.
  3. Create an object by calling the class DictReader of the module csv . Reader class reads the file line by line and returns the object.
  4. Run a loop for showing the data.

You can check the python CSV reader code using the module csv on GitHub.

Reading CSV Using Pandas Library

Steps for reading a CSV file using Panda Library:

  1. Import pandas module.
  2. Use read_csv function and pass the file to this function as an argument.
  3. Print data.

You can check the python CSV reader code using the Pandas module on GitHub.

Leave a Reply

Your email address will not be published. Required fields are marked *