Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #68889 > unrolled thread
| Started by | Vincent Davis <vincent@vincentdavis.net> |
|---|---|
| First post | 2014-03-24 11:50 -0600 |
| Last post | 2014-03-24 11:50 -0600 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
Merge/append CSV files with different headers Vincent Davis <vincent@vincentdavis.net> - 2014-03-24 11:50 -0600
| From | Vincent Davis <vincent@vincentdavis.net> |
|---|---|
| Date | 2014-03-24 11:50 -0600 |
| Subject | Merge/append CSV files with different headers |
| Message-ID | <mailman.8454.1395683453.18130.python-list@python.org> |
[Multipart message — attachments visible in raw view] — view raw
I have several csv file I need to append (vertically). They have different
but overlapping headers. For example;
file1 headers ['a', 'b', 'c']
file2 headers ['d', 'e']
file3 headers ['c', 'd']
Is there a better way than this
import csv
def merge_csv(fileList, newFileName):
allHeaders = set([])
for afile in fileList:
with open(afile, 'rb') as csvfilesin:
eachheader = csv.reader(csvfilesin, delimiter=',').next()
allHeaders.update(eachheader)
print(allHeaders)
with open(newFileName, 'wb') as csvfileout:
outfile = csv.DictWriter(csvfileout, allHeaders)
outfile.writeheader()
for afile in fileList:
print('***'+afile)
with open(afile, 'rb') as csvfilesin:
rows = csv.DictReader(csvfilesin, delimiter=',')
for r in rows:
print(allHeaders.issuperset(r.keys()))
outfile.writerow(r)
Vincent Davis
Back to top | Article view | comp.lang.python
csiph-web