0
votes

I have a CSV file that is being constantly appended. It has multiple headers and the only common thing among the headers is that the first column is always "NAME".

How do I split the single CSV file into separate CSV files, one for each header row?

here is a sample file:

"NAME","AGE","SEX","WEIGHT","CITY"
"Bob",20,"M",120,"New York"
"Peter",33,"M",220,"Toronto"
"Mary",43,"F",130,"Miami"
"NAME","COUNTRY","SPORT","NUMBER","SPORT","NUMBER"
"Larry","USA","Football",14,"Baseball",22
"Jenny","UK","Rugby",5,"Field Hockey",11
"Jacques","Canada","Hockey",19,"Volleyball",4
"NAME","DRINK","QTY"
"Jesse","Beer",6
"Wendel","Juice",1
"Angela","Milk",3
4
Do you know how to read the rows using the csv module? I mean, do you have the code working except for the splitting part? - DSM
what would you do in a case where a different CSV header had the same number of elements as the previous? How do you differentiate between header and non-header? e.g. "NAME","DRINK","QTY"\n twice in a row - JDong
Don't know Python. Just trying to quickly resolve a problem and have this as an option. As for knowing which row is a header - "NAME" will always mean the beginning of a new header row. Two rows starting with "Name" should mean that an empty file should be created. Let me add - I'm sorry for the "mooching", but I couldn't find an example close enough. - Ed Dantes
Are you on linux? If all you need is the result, you can do this in one line using csplit. - DSM

4 Answers

2
votes

If the size of the csv files is not huge -- so all can be in memory at once -- just use read() to read the file into a string and then use a regex on this string:

import re

with open(ur_csv) as f:
    data=f.read()
    chunks=re.finditer(r'(^"NAME".*?)(?=^"NAME"|\Z)',data,re.S | re.M)
    for i, chunk in enumerate(chunks, 1):
        with open('/path/{}.csv'.format(i), 'w') as fout:
            fout.write(chunk.group(1))

If the size of the file is a concern, you can use mmap to create something that looks like a big string but is not all in memory at the same time.

Then use the mmap string with a regex to separate the csv chunks like so:

import mmap
import re

with open(ur_csv) as f:
    mf=mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
    chunks=re.finditer(r'(^"NAME".*?)(?=^"NAME"|\Z)',mf,re.S | re.M)
    for i, chunk in enumerate(chunks, 1):
        with open('/path/{}.csv'.format(i), 'w') as fout:
            fout.write(chunk.group(1))

In either case, this will write all the chunks in files named 1.csv, 2.csv etc.

1
votes

Copy the input to a new output file each time you see a header line. Something like this (not checked for errors):

partNum = 1
outHandle = None
for line in open("yourfile.csv","r").readlines():
  if line.startswith('"NAME"'):
    if outHandle is not None:
      outHandle.close()
    outHandle = open("part%d.csv" % (partNum,), "w")
    partNum += 1
  outHandle.write(line)
outHandle.close()

The above will break if the input does not begin with a header line or if the input is empty.

1
votes

You can use the python csv package to read your source file and write multile csv files based on the rule that if element 0 in your row == "NAME", spawn off a new file. Something like this...

import csv

outfile_name = "out_%.csv"
out_num = 1

with open('nameslist.csv', 'rb') as csvfile:
    csvreader = csv.reader(csvfile, delimiter=',')
    csv_buffer = []

    for row in csvreader:
        if row[0] != "NAME":
            csv_buffer.append(row)
        else:
            with open(outfile_name % out_num, 'wb') as csvout:
                    for b_row in csv_buffer:
                        csvout.writerow(b_row)
                    out_num += 1
                    csv_buffer = [row]

P.S. I haven't actually tested this but that's the general concept

0
votes

Given the other answers, the only modification that I would suggest would be to open using csv.DictReader. pseudo code would be like this. Assuming that the first line in the file is the first header

Note that this assumes that there is no blank line or other indicator between the entries so that a 'NAME' header occurs right after data. If there were a blank line between appended files the you could use that as an indicator to use infile.fieldnames() on the next row. If you need to handle the inputs as a list, then the previous answers are better.

ifile = open(filename, 'rb')
infile = cvs.Dictreader(ifile)

infields = infile.fieldnames

filenum = 1
ofile = open('outfile'+str(filenum), 'wb')
outfields = infields # This allows you to change the header field
outfile = csv.DictWriter(ofile, fieldnames=outfields, extrasaction='ignore')
outfile.writerow(dict((fn, fn) for fn in outfields))

for row in infile:
  if row['NAME'] != 'NAME':
    #process this row here and do whatever is needed
  else:
    close(ofile)
    # build infields again from this row
    infields = [row["NAME"], ...] # This assumes you know the names & order
    # Dict cannot be pulled as a list and keep the order that you want.
    filenum += 1
    ofile = open('outfile'+str(filenum), 'wb')
    outfields = infields # This allows you to change the header field
    outfile = csv.DictWriter(ofile, fieldnames=outfields, extrasaction='ignore')
    outfile.writerow(dict((fn, fn) for fn in outfields))

# This is the end of the loop. All data has been read and processed
close(ofile)
close(ifile)

If the exact order of the new header does not matter except for the name in the first entry, then you can transfer the new list as follows:

infileds = [row['NAME']
for k in row.keys():
  if k != 'NAME':
    infields.append(row[k])

This will create the new header with NAME in entry 0 but the others will not be in any particular order.