import csv
from itertools import groupby
for key, rows in groupby(csv.reader(open('foo.csv')), lambda row: row[0]):
    with open('%s.txt' % key, 'w') as output:
        for row in rows:
            output.write(','.join(row) + '\n')
How to split a huge csv file based on content of first column?