Beginner Level
Intermediate Level
Advanced Level
Introduction
Reading CSV files in Python programming language is a fundamental skill for data analysis and manipulation, as many data sources come in the form of CSV files. In this tutorial, we will explore the basics of how to read CSV files using Python. We will cover different methodologies for importing CSV files, the different ways of handling CSV files with different structures and how to parse CSV files in Python. By the end of this tutorial, you will be able to work efficiently with CSV files in Python and be able to incorporate the data into your projects.
Table of Contents :
- Reading a CSV File in Python
- Reading a specific column of a CSV file
- Reading a CSV File using the DictReader Class
Reading a CSV File in Python
- The
csv
module in Python can be used to read and write to CSV files. - To read a CSV file in Python, open the file with the
open()
function and pass its file object to thecsv.reader()
method. - Code Sample :
import csv
# Reading a csv file
with open('data.csv') as file:
reader = csv.reader(file)
for row in reader:
print(row)
Reading a specific column of a CSV file
- We can read specific columns of a CSV file by accessing their index in each row.
- Code Sample :
import csv
# Reading specific columns of a csv file
with open('data.csv') as file:
reader = csv.reader(file)
for row in reader:
print(row[0], row[2])
Reading a CSV File using the DictReader Class
- The
csv.DictReader()
class in Python can be used to read a CSV file as a dictionary. - The keys of the dictionary are taken from the CSV file's header.
- Code Sample :
import csv
# Reading a csv file using DictReader
with open('data.csv') as file:
reader = csv.DictReader(file)
for row in reader:
print(row['Name'], row['Age'])
Prev. Tutorial : Python for csv files
Next Tutorial : Writing to csv files