How to read a CSV file in Python

A comma separated values (CSV) file is a plain text file, used to arrange tabular data, typically found in spreadsheets or databases. CSV files are frequently used as they are accessible in Microsoft Excel and data from a CSV file may also be imported in a database. The ease with which data from a CSV file can be parsed is why it is used commonly.

CSV files follow a particular format to store data. Each data item is separated by a comma.

Basic structure of a CSV file

  Column 1   ,   Column 2   , Column 3 ...
Row 1 Data 1 , Row 1 Data 2 , Row 1 Data 3 ...
Row 2 Data 1 , Row 2 Data 2 , Row 2 Data 3 ...

The first row represents the name of the column and each of the following rows represents the data.

Note: The most frequently used delimiter is a comma, however, other delimiters such as colon, semi-colon etc may also be used.

CSV file in Python

Python allows users to import data from a CSV file. This can be done as follows:

  1. Import the csv library
  2. Open the desired CSV file
  3. Store data into a variable using the built-in csv.reader function
  4. Loop through each row of data stored in the variable
  5. Close the CVS file

Look at the following code to see how all these steps are put together.

Suppose the following data is stored in the file:

svg viewer
main.py
data.csv
Name, Age, Department
John, 26, Accounts
Mike, 30, HR
James, 29, IT
Oliver,32, IT

The data obtained from a CSV file can be used in a variety of ways, depending on the user’s needs.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved