-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrandomize-csv.py
executable file
·48 lines (37 loc) · 1.2 KB
/
randomize-csv.py
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
47
48
#!/usr/bin/env python3
import csv
import re
from argparse import ArgumentParser
from collections import defaultdict
from random import shuffle
from pprint import pprint
config = None
limit = -1
def randomize():
with open(config.srcfile, "r") as csvfile:
reader = csv.reader(csvfile)
headers = next(reader)
values = defaultdict(list)
# read CSV into COLUMNS ...
for rowcount, row in enumerate(reader):
# print(row)
for colname, val in zip(headers, row):
values[colname].append(val)
if rowcount == limit:
break
# shuffle columns
for _, col in values.items():
shuffle(col)
# transpose columns into rows
rows = zip(*[values[hd] for hd in headers])
# overwrite old file with shuffled values
with open(config.srcfile, "w") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(headers)
for row in rows:
writer.writerow(row)
if __name__ == "__main__":
parser = ArgumentParser(description="Randomize CSV files")
parser.add_argument("srcfile", help="Which file to randomize")
config = parser.parse_args()
randomize()