bigTree
bigTree

Reputation: 2183

Write csv file column by column

I want to write a csv file column by column using python. I read my data from a first csv file and, if the header is 'ok', then I want to copy the column. I tried the following:

         for column in zip(*data):
            l= []
            if column[0] == 'ok' :
                for k in column:
                    l.append(k)

            my_writer.writerow(zip(*l))

But it raises the error:

    wrt.writerow(zip(*l))
_csv.Error: sequence expected

I then tried with writerows instead of writerow, but the result is clearly not what I expect: The first column contains parts of the names of the headers...

Any idea?

Upvotes: 0

Views: 456

Answers (1)

Paco
Paco

Reputation: 4708

First of all, you have a syntax error: if column[0] = 'ok' :, it should be if column[0] == 'ok':

Then you will need to create an object that will create a row, with one element per row on the first iteration (for the first column), and then you keep appending your result to it, until you reach the end.

At this point you can write into the csv file.

Also, have a look at the CSV module.

Upvotes: 1

Related Questions