Working with ZIP and CSV Files in Python


Introduction

Handling ZIP and CSV files in Python is essential for data engineers, developers, and analysts. The Python standard library provides powerful modules like:

  • zipfile – to read/write ZIP archives
  • csv – to read/write CSV files (Comma-Separated Values)


How to Work with ZIP Files in Python


1. Importing zipfile Module

import zipfile

Create a ZIP File

import zipfile

with zipfile.ZipFile('archive.zip', 'w') as zipf:
    zipf.write('file1.txt')
    zipf.write('file2.txt')
print("ZIP file created.")

Output:

ZIP file created.

Extract a ZIP File

with zipfile.ZipFile('archive.zip', 'r') as zipf:
    zipf.extractall('extracted_files')
print("Files extracted.")

Output:

Files extracted.

List Files in a ZIP Archive

with zipfile.ZipFile('archive.zip', 'r') as zipf:
    print(zipf.namelist())

Output:

['file1.txt', 'file2.txt']

Check if ZIP File is Corrupted

with zipfile.ZipFile('archive.zip', 'r') as zipf:
    if zipf.testzip() is None:
        print("ZIP file is good!")
    else:
        print("Corrupt file found.")


How to Work with CSV Files in Python


1. Importing csv Module

import csv

Read CSV File

with open('data.csv', newline='') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        print(row)

Output (if data.csv contains):

Name,Age
John,28
Alice,30

Would print:

['Name', 'Age']
['John', '28']
['Alice', '30']

Write CSV File

with open('output.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['Name', 'Age'])
    writer.writerow(['John', 28])
    writer.writerow(['Alice', 30])

Output:

A file output.csv with:
Name,Age
John,28
Alice,30

Read CSV as Dictionary

with open('data.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['Name'], row['Age'])

Output:

John 28
Alice 30

Write CSV from Dictionary

with open('output_dict.csv', 'w', newline='') as csvfile:
    fieldnames = ['Name', 'Age']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'Name': 'John', 'Age': 28})
    writer.writerow({'Name': 'Alice', 'Age': 30})


Combining ZIP + CSV: Extract and Read CSV from ZIP

import zipfile
import csv

with zipfile.ZipFile('data.zip', 'r') as zipf:
    zipf.extract('data.csv')

with open('data.csv', newline='') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        print(row)