-
Notifications
You must be signed in to change notification settings - Fork 27
/
utils.py
72 lines (67 loc) · 3.03 KB
/
utils.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import os
import glob
import csv
year = '2018'
election = '20181106'
path = election+'*precinct.csv'
output_file = election+'__tx__general__precinct.csv'
def generate_headers(year, path):
os.chdir(year)
vote_headers = []
for fname in glob.glob(path):
print(fname)
with open(fname, "r") as csvfile:
reader = csv.reader(csvfile)
headers = next(reader)
print(list(fname + ': ' + h for h in headers if h not in ['county','precinct', 'office', 'district', 'candidate', 'party','votes','election_day', 'early_voting']))
#vote_headers.append(h for h in headers if h not in ['county','precinct', 'office', 'district', 'candidate', 'party'])
# with open('vote_headers.csv', "w") as csv_outfile:
# outfile = csv.writer(csv_outfile)
# outfile.writerows(vote_headers)
def generate_offices(year, path):
os.chdir(year)
offices = []
for fname in glob.glob(path):
with open(fname, "r") as csvfile:
print(fname)
reader = csv.DictReader(csvfile)
for row in reader:
if not row['office'] in offices:
offices.append(row['office'])
with open('offices.csv', "w") as csv_outfile:
outfile = csv.writer(csv_outfile)
outfile.writerows(offices)
def generate_consolidated_file(year, path, output_file):
results = []
os.chdir(year)
for fname in glob.glob(path):
print(fname)
with open(fname, "rU") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if row['office'].strip() in ['Governor', 'Comptroller', 'Attorney General', 'U.S. Senate', 'U.S. House', 'State Senate', 'State Assembly']:
if 'election_day' in row:
election_day = row['election_day']
else:
election_day = None
if 'absentee_hc' in row:
absentee_hc = row['absentee_hc']
else:
absentee_hc = None
if 'absentee' in row:
absentee = row['absentee']
else:
absentee = None
if 'machine_votes' in row:
machine_votes = row['machine_votes']
else:
machine_votes = None
if 'affidavit' in row:
affidavit = row['affidavit']
else:
affidavit = None
results.append([row['county'], row['precinct'], row['office'], row['district'], row['candidate'], row['party'], row['votes'], election_day, absentee, machine_votes, absentee_hc, affidavit])
with open(output_file, "w") as csv_outfile:
outfile = csv.writer(csv_outfile)
outfile.writerow(['county','precinct', 'office', 'district', 'candidate', 'party', 'votes', 'election_day', 'absentee', 'machine_votes', 'absentee_hc', 'affidavit'])
outfile.writerows(results)