Member-only story

Effortlessly Manipulate CSV and Excel Files with Python: A Practical Tutorial

Simplify Your Workflow Using Built-in Libraries

Max N
2 min readMar 13, 2024
Photo by Ed Hardie on Unsplash

Working with delimited text files, particularly comma-separated values (CSV), is commonplace in many industries. Fortunately, Python offers robust tools for reading, writing, and manipulating both CSV and Microsoft Excel files effortlessly. Let’s dive into csv and openpyxl libraries, exploring how to utilize them effectively via practical code samples.

Reading and Writing CSV Files

The csv module provides extensive functionality for managing CSV files. To read from one, open it using a csv.reader instance wrapped around a file handler:

import csv

with open('sample.csv', mode='r') as file:
reader = csv.reader(file)

# Skip header row
next(reader)

for row in reader:
print(row)

# Output: ['Alice', 'Sales', 'NY', '1000']
# ['Bob', 'Marketing', 'LA', '2000']
# ['Charlie', 'IT', 'SF', '3000']

Writing to a new CSV file requires creating a csv.writer instance tied to a writable file handler:

headers = ['Name', 'Department', 'City', 'Salary']
rows = [['David', 'HR', 'CHI', '1500'], ['Eva', 'Finance', 'ATL', '2500']]

with open('new_sample.csv'…

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet