PythonFile HandlingCSV File Handling

CSV File Handling in Python

CSV (Comma-Separated Values) files are a common data format used for storing tabular data. Python provides the built-in csv module for handling these files.


Introduction to CSV Files

A CSV file contains rows of data separated by commas (or other delimiters). It is often used for data exchange between applications like spreadsheets and databases.

Example CSV Content

Name,Age,City
Alice,25,New York
Bob,30,San Francisco
Charlie,35,Chicago

Using Python’s Built-in csv Module

Python’s csv module makes it easy to read and write CSV files. It includes classes like csv.reader and csv.writer for structured data manipulation.

Importing the csv Module

import csv

Reading CSV Files with csv.reader

The csv.reader class reads the contents of a CSV file and converts it into a list of rows.

Example: Reading a CSV File

import csv
 
with open("example.csv", "r") as csv_file:
    csv_reader = csv.reader(csv_file)
    for row in csv_reader:
        print(row)

Output

['Name', 'Age', 'City']
['Alice', '25', 'New York']
['Bob', '30', 'San Francisco']
['Charlie', '35', 'Chicago']

Writing CSV Files with csv.writer

The csv.writer class writes data to a CSV file row by row.

Example: Writing a CSV File

import csv
 
data = [
    ["Name", "Age", "City"],
    ["Alice", 25, "New York"],
    ["Bob", 30, "San Francisco"],
    ["Charlie", 35, "Chicago"]
]
 
with open("output.csv", "w", newline="") as csv_file:
    csv_writer = csv.writer(csv_file)
    csv_writer.writerows(data)

This creates a file output.csv with the following content:

Name,Age,City
Alice,25,New York
Bob,30,San Francisco
Charlie,35,Chicago

Reading and Writing with Custom Delimiters

You can specify a custom delimiter using the delimiter parameter in both csv.reader and csv.writer.

Example: Using a Tab Delimiter

import csv
 
# Writing with a tab delimiter
data = [
    ["Name", "Age", "City"],
    ["Alice", 25, "New York"],
    ["Bob", 30, "San Francisco"]
]
 
with open("tab_delimited.csv", "w", newline="") as csv_file:
    csv_writer = csv.writer(csv_file, delimiter="\t")
    csv_writer.writerows(data)
 
# Reading the tab-delimited file
with open("tab_delimited.csv", "r") as csv_file:
    csv_reader = csv.reader(csv_file, delimiter="\t")
    for row in csv_reader:
        print(row)

Practical Applications

  1. Data Import/Export: Exchange data between applications.
  2. Data Preprocessing: Process CSV data for machine learning or analytics.
  3. Dynamic Reports: Generate CSV reports from databases or APIs.

Try It Yourself

Problem 1: Read and Print Specific Columns

Write a program to read a CSV file and print only the “Name” and “City” columns.

Show Solution
import csv
 
with open("example.csv", "r") as csv_file:
    csv_reader = csv.reader(csv_file)
    next(csv_reader)  # Skip the header row
    for row in csv_reader:
        print(f"Name: {row[0]}, City: {row[2]}")

Problem 2: Append Data to an Existing CSV File

Write a program to add a new row to an existing CSV file.

Show Solution
import csv
 
new_data = ["Diana", 28, "Seattle"]
 
with open("output.csv", "a", newline="") as csv_file:
    csv_writer = csv.writer(csv_file)
    csv_writer.writerow(new_data)

Python’s csv module provides a straightforward way to work with CSV files for both basic and advanced use cases. Experiment with reading and writing CSV files to build robust data handling workflows!


Pyground

Play with Python!

Output: