Python CSV: Read and Write CSV Files

The CSV (Comma Separated Values) format is a common and straightforward way to store tabular data. To represent a CSV file, it should have the .csv file extension.

Now, let's proceed with an example of the info .csv file and its data.

SN, Name,    City
1,  Michael, New Jersey
2,  Jack,    California

Working With CSV Files in Python

Python provides a dedicated csv module to work with csv files. The module includes various methods to perform different operations.

However, we first need to import the module using:

import csv

Read CSV Files with Python

The csv module provides the csv.reader() function to read a CSV file.

Suppose we have a csv file named people.csv with the following entries.

Name,   Age, Profession
Jack,   23,  Doctor
Miller, 22,  Engineer

Now, let's read this csv file.

import csv

with open('people.csv', 'r') as file:
    reader = csv.reader(file)

    for row in reader:
        print(row)

Output

['Name', 'Age', 'Profession']
['Jack', '23', 'Doctor']
['Miller', '22', 'Engineer']

Here, we have opened the people.csv file in reading mode using:

with open(airtravel.csv', 'r') as file:

We then used the csv.reader() function to read the file. To learn more about reading csv files,