-
Notifications
You must be signed in to change notification settings - Fork 801
Expand file tree
/
Copy pathmy_merge_csv.py
More file actions
30 lines (26 loc) · 975 Bytes
/
my_merge_csv.py
File metadata and controls
30 lines (26 loc) · 975 Bytes
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
import csv
def merge_csv(arrayOfCsvFileNameInput, csvFileNameOutput):
inputEntries = {}
for fileName in arrayOfCsvFileNameInput:
with open(fileName, "r") as f:
inputEntries[fileName] = list(csv.DictReader(f))
fieldNameSet = set({})
for j in inputEntries.values():
fieldNameSet = fieldNameSet.union(set(j[1].keys()))
resLine = {}
resultsOutput = []
for inputFileValue in inputEntries.values():
for lineOfResults in inputFileValue:
for fieldOfTheSet in fieldNameSet:
if fieldOfTheSet in inputFileValue[1].keys():
resLine[fieldOfTheSet] = lineOfResults[fieldOfTheSet]
else:
resLine[fieldOfTheSet] = None
resultsOutput.append(resLine)
resLine = {}
with open(csvFileNameOutput, "w") as f:
writer = csv.writer(f)
writer.writerow(list(fieldNameSet))
for row in resultsOutput:
writer.writerow(row.values())
merge_csv(['class1.csv', 'class2.csv'], 'all_students.csv')