Last Updated: 31-October-2016

Here's a quick script for dealing with merged CSV cells. Basically, if you need to unmerge a bunch of cells and duplicate what the value was into the split cells, here's an easy was to do it with Python.

I've just had to do this over a ducument with almost 2 thousand rows, so I knocked this together and though I'd share it.


# -*- coding: utf-8-*-
import csv

def get_index(lis):
	''' returns the index values 
	for empty strings.
	'''
    results = []
    for count, item in enumerate(lis):
        if item == '':
            results.append(count)
    return results      

with open('input.csv') as f:
	data = csv.reader(f)
	last_row = ''
	for row in data:
		if '' not in row:
			last_row = row
		else:
			for i in get_index(row):
				row[i] = last_row[i]

		with open('output.csv', 'a') as out:
			w = csv.writer(out)
			w.writerow(row)

About the author

Image

Craig Addyman @craigaddyman
Head of Digital Marketing. Python Coder.