Question

Here is my code.csv file:

one,two,three
1,2,3
2,3,4
3,4,5

and code2.csv file:

,two,three
,2,3
,3,4
,4,5

this is my code.py file:

import csv

with open('code.csv', 'rb') as input, open('result.csv', 'wb') as output:
        reader = csv.DictReader(input)
        rows = [row for row in reader]
        writer = csv.writer(output, delimiter = ',')

        writer.writerow(["new_one", "new_two", "new_three"])

        for row in rows:
                if 'two' in row:
                        writer.writerow(['',row["two"]])

        for row in rows:
                if 'one' in row:
                        writer.writerow([row["one"]])

The problem is that output is printed in different rows:

new_one,new_two,new_three
,2
,3
,4
1
2
3

How can I make the

for row in rows:
                    if 'one' in row:
                            writer.writerow([row["one"]])

to be printed like this

new_one,new_two,new_three
1,2
2,3
3,4

Without having to type it like this

 for row in rows:
                if 'one' in row and 'two' in row:
                        writer.writerow([row["one"],row["two"]])

Now if i would have code2.csv instead of code.csv, the latter (if 'one' in row and 'two' in row:) would give me error "'one' not found". So I need to have something like maybe "for row in rows[1]:" or something. Obviously that doesn't work, but something similar?

Was it helpful?

Solution

You must write row by row, not column by column. I think this should do it:

    for row in rows:
        writer.writerow([row.get("one", ""), row.get("two", "")])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top