Working with CSV Files in Python

Tutorial 2 of 5

1. Introduction

In this tutorial, we will explore how to handle CSV (Comma Separated Values) files in Python. CSV files are a popular data format in programming and are used for storing tabular data in plain text, making them easy to import into a spreadsheet or database.

Goals: By the end of this tutorial, you will learn how to read, write, and manipulate data from CSV files using Python’s built-in csv module.

Prerequisites: You should have a basic understanding of Python programming. Familiarity with file handling in Python would be beneficial but is not required.

2. Step-by-Step Guide

Python provides a built-in module called csv to read and write CSV files. It offers various functions and classes to handle CSV files.

Reading a CSV file: Python’s csv.reader() function is used to read a CSV file.

Writing to a CSV file: Python’s csv.writer() function is used to write into a CSV file.

Manipulating CSV data: Python's csv module also provides various methods like writerow(), writerows(), DictReader, and DictWriter to manipulate CSV data.

3. Code Examples

Example 1: Reading a CSV file

import csv

# Open a CSV file
with open('file.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

In this example, we first import the csv module. Then, we open the CSV file in read mode ('r'). The csv.reader() function is used to read the file. We then iterate through each row in the file and print it.

Example 2: Writing to a CSV file

import csv

# Data to be written
data = [['Name', 'Age'], ['John', '20'], ['Doe', '30']]

# Open a CSV file in write mode
with open('file.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)

In this example, we first define the data to be written. Then, we open the CSV file in write mode ('w') and use csv.writer() to get a writer object. The writerows() method writes all data rows at once.

4. Summary

In this tutorial, we learned how to handle CSV files in Python using the csv module. We covered how to read, write, and manipulate data stored in CSV format.

To expand your knowledge, you can explore how to handle CSV files with different delimiters, reading CSV files into a dictionary with csv.DictReader(), and writing CSV files from a dictionary with csv.DictWriter().

5. Practice Exercises

Exercise 1: Read a CSV file and print the first five lines.

Exercise 2: Write a list of dictionaries into a CSV file.

Exercise 3: Read a CSV file, modify a specific column, and write it into a new CSV file.

These exercises will help you practice the skills learned in this tutorial. The solutions are not provided here to encourage self-learning. If you get stuck, you can refer back to the tutorial or search online for help. Happy coding!