Member-only story
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'…