Claude S.
Claude S.

Reputation: 21

Extract rows and save to multiple csv files

I am trying to solve the following problem using Python: I've a table (csv) from which I want to extract consecutively row 1 + 2, then row 1 + 3, then row 1 + 4, etc. The extracts should be saved again as csv file and named according to the first string in the 2nd row to be extracted (2, 3, 4, 5,...). Now my question - is python the right tool to do this and is there any example code available?

Thanks a lot in advance for any help & hints!

Claude S.

+ Clarification:

Thanks for the feedback - actually I was trying to use the csv module to open and read the table using this code:

import csv
import sys

f = open(sys.argv[1], 'rt')
try:
    reader = csv.reader(f)
    for row in reader:
        print row

Now I am not sure how to select and write the required rows... sorry for the beginners kind of question. Claude S.

Upvotes: 2

Views: 1592

Answers (2)

Carl F.
Carl F.

Reputation: 7056

I'm not convinced that you need the csv module (unless the first column could contain quotes and commas). If your file format is simple, just use split.

fname = argv[1]
with open(fname) as f:
    header = f.readline()
    # parse the rest of the lines. 
    for line in f:
        out_name = line.split(',')[0]
        with open(out_name, 'wb') as o:
            o.write(header)
            o.write(line)

Upvotes: 0

Facundo Casco
Facundo Casco

Reputation: 10585

fname = argv[1]
with open(fname) as i:
    reader = csv.reader(i)

    first_row = next(reader)
    for cur_row in reader:
        out_name = cur_row[0]
        with open(out_name, 'wb') as o:
            writer = csv.writer(o)
            writer.writerow(first_row)
            writer.writerow(cur_row)

Hope it helps

Upvotes: 1

Related Questions