Python / Python File Handling

Working with CSV Files in Python

In this tutorial, you’ll learn how to handle CSV files in Python. We’ll cover how to read, write, and manipulate data stored in CSV format using Python’s built-in csv module.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Covers reading and writing files, working with CSVs, and managing file objects.

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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Fake User Profile Generator

Generate fake user profiles with names, emails, and more.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help