summaryrefslogtreecommitdiff
path: root/split-csv.py
blob: 62dc15976db81f6f2c5cb5b72f4831340155c23d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import os
import sys
import csv
from math import ceil
import subprocess
import random

import click

@click.command()
@click.option('--count', '-c', default=2, help='Number of subdivisions.')
@click.option('--shuffle/--no_shuffle', default=False, help='Whether to shuffle.')
@click.argument('filename')
def split_csv(count, shuffle, filename):
  """Split a CSV into groups."""
  with open(filename, 'r') as f:
    reader = csv.reader(f)
    lines = list(reader)
    keys = lines[0]
    lines = lines[1:]

    fn, ext = os.path.splitext(filename)
    if shuffle:
      random.shuffle(lines)
    for index, chunk in enumerate(chunks(lines, count)):
      out_fn = fn + '-' + str(index+1) + ext
      write_csv(out_fn, keys, chunk)
      # sys.exit(1)

# Write a CSV
def write_csv(fn, keys, chunk):
  print(fn)
  with open(fn, 'w') as f:
    writer = csv.writer(f)
    if keys is not None:
      writer.writerow(keys)
    for row in chunk:
      writer.writerow(row)

# Split an array into chunks
def chunks(l, n):
  n = max(1, ceil(len(l) / n))
  return (l[i:i+n] for i in range(0, len(l), n))

if __name__ == '__main__':
  split_csv()