Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #68890

Re: Merge/append CSV files with different headers

From Mark Lawrence <breamoreboy@yahoo.co.uk>
Subject Re: Merge/append CSV files with different headers
Date 2014-03-24 18:24 +0000
References <CALyJZZWmAWP=STfZGpvN_NexxS=7DA9GrxOAC+2ibUNgkJtM1Q@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.8455.1395685473.18130.python-list@python.org> (permalink)

Show all headers | View raw


On 24/03/2014 17:50, Vincent Davis wrote:
> 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
>

I haven't looked too hard at your code but guess you could simplify it 
by using the fieldnames parameter to the DictReader class or making use 
of the Sniffer class.  See 
http://docs.python.org/3/library/csv.html#module-csv


-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection is active.
http://www.avast.com

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Merge/append CSV files with different headers Mark Lawrence <breamoreboy@yahoo.co.uk> - 2014-03-24 18:24 +0000

csiph-web