« Back to Index

[Handling CSV files in Python]

View original Gist on GitHub

Tags: #csv #python

1. Handling CSV files in Python (unsorted).py

import csv
import re

TEMPLATE = """
- original: '{}'
  redirect: '{}'"""

with open("/Users/integralist/Downloads/example.csv") as csvfile:
    reader = csv.DictReader(csvfile)

    for row in reader:
        for k, v in row.items():
            if k == "tasty.co link" and len(v) > 10:
                match = re.search("^(https?://)?tasty.co(?P<path>.+)", v)
                if match:
                    print(TEMPLATE.format(row["slug"], match.group("path")))

2. Handling CSV files in Python (sorted).py

import csv
import operator
import re

TEMPLATE = """
- original: '{}'
  redirect: '{}'"""

with open("/Users/integralist/Downloads/example.csv") as csvfile:
    reader = csv.reader(csvfile)
    sortedlist = sorted(reader, key=operator.itemgetter(1))  # sort by column index 1 (i.e. "slug")

    for row in sortedlist:
        if not row[1].startswith("/"):  # skip the header row (i.e. "slug")
            continue

        if len(row[4]) > 10:  # there is an appropriate redirect path
            match = re.search("^(https?://)?tasty.co(?P<path>.+)", row[4])
            if match:
                print(TEMPLATE.format(row[1], match.group("path")))