Using the inbuilt python CSV libary to read csv files.
Python’s built-in csv
module provides a simple way to read CSV files. Here’s how you can use it:
Reading a CSV File
Using csv.reader()
import csv
# Open the CSV file
with open('example.csv', mode='r', newline='') as file:
reader = csv.reader(file)
# Iterate over the rows
for row in reader:
print(row) # Each row is a list
csv.reader(file)
returns an iterable reader object.- Each row is read as a list of strings.
Example 2: Using csv.DictReader()
import csv
with open('example.csv', mode='r', newline='') as file:
reader = csv.DictReader(file)
for row in reader:
print(row) # Each row is an ordered dictionary
csv.DictReader(file)
treats the first row as column headers and returns each row as a dictionary.
Here is the source if you want to look into the python csv module in detail!