python
  1. python-read-csv-file

Python Read CSV File

CSV stands for Comma Separated Values. It is a simple format for storing data in tabular form where each row represents a record, and each column represents a field. In Python, the csv module is used to read and write data in CSV format.

Syntax

The basic syntax to read a CSV file in Python is:

import csv

with open('filename.csv', newline='') as csvfile:
    csvreader = csv.reader(csvfile, delimiter=',', quotechar='|')
    for row in csvreader:
        print(', '.join(row))

Example

Suppose we have a CSV file named data.csv with the following contents:

Name, Age, Gender
John, 28, Male
Alice, 23, Female
Bob, 35, Male

The following Python code reads this file and prints its contents:

import csv

with open('data.csv', newline='') as csvfile:
    csvreader = csv.reader(csvfile, delimiter=',', quotechar='|')
    for row in csvreader:
        print(', '.join(row))

Output

Name, Age, Gender
John, 28, Male
Alice, 23, Female
Bob, 35, Male

Explanation

In the above example, we have imported the csv module. Then we have used the with statement to open the CSV file. The newline='' argument is used to prevent extra blank rows from being included in the output.

Next, we have created a csvreader object using the csv.reader() function, which takes three arguments:

  • csvfile: the CSV file object.
  • delimiter: the character that separates the fields in the CSV file (default is ,).
  • quotechar: the character used to quote fields that contain special characters (default is ").

Finally, we have used a for loop to iterate over the rows in the CSV file. The join() method is used to convert each row into a string with fields separated by a , character.

Use

Reading CSV files is a common task in data analysis and data science projects. You can use Python's csv module to read CSV files and extract data for further analysis.

Important Points

  • CSV files are a popular format for storing and exchanging data.
  • Python's csv module provides functions for reading and writing CSV files.
  • The csv.reader() function is used to create a reader object that can iterate over the rows in a CSV file.
  • The delimiter parameter specifies the character that separates the fields in the CSV file (default is ,).
  • The quotechar parameter specifies the character used to quote fields that contain special characters (default is ").

Summary

In this tutorial, we have learned how to read a CSV file in Python using the csv module. We have also covered the syntax and important points related to reading CSV files in Python.

Published on: