In this tutorial, we will learn how to read a CSV (Comma Separated Values) file using Python. CSV is a widely used text-based format for representing tabular data. Python provides a built-in module called csv
for reading and writing CSV files. We will explore different methods using this module to read CSV files and process the data.
Prerequisites
Before getting started, make sure you have a data file in CSV format. You can use the example below, save it as ‘sample.csv’:
Name,Age,Gender,Occupation John,30,Male,Software Engineer Jane,28,Female,Data Analyst Steve,35,Male,Product Manager Sam,24,Female,Marketing Coordinator
Step 1: Importing the csv module
First, we need to import the csv
module in our Python script. Include the following line at the beginning of your script:
1 |
import csv |
Step 2: Open the CSV file
To open the CSV file, we can use the built-in open()
function, which accepts the file path as a parameter, and an optional ‘mode’ parameter. In our case, we will use the ‘r’ mode for reading the file:
1 |
file = open('sample.csv', 'r') |
Step 3: Read the file using csv.reader()
Now we can use the reader()
function from the csv
module to read the contents of our file. The reader()
function takes the file object as a parameter and returns an iterable object that we can loop through to read each row in the file:
1 |
csv_reader = csv.reader(file) |
Step 4: Process the data
We can now process the data by iterating over the csv_reader
object, which will yield each row as a list.
For example, let’s print each row in the CSV file:
1 2 |
for row in csv_reader: print(row) |
This will give us the output:
['Name', 'Age', 'Gender', 'Occupation'] ['John', '30', 'Male', 'Software Engineer'] ['Jane', '28', 'Female', 'Data Analyst'] ['Steve', '35', 'Male', 'Product Manager'] ['Sam', '24', 'Female', 'Marketing Coordinator']
Full Code
1 2 3 4 5 6 7 8 9 |
import csv file = open('sample.csv', 'r') csv_reader = csv.reader(file) for row in csv_reader: print(row) file.close() |
Conclusion
In this tutorial, we’ve learned how to read a CSV file using Python’s built-in csv
module. We imported the module, opened the file for reading, used the reader()
function to read the file, and processed the data by iterating over each row.
This basic method can be further customized to process and manipulate the data according to your specific needs.