2

I want to write a list to the third column of a csv file.

list = ['cat', 'dog', 'duck', ..., 'goat']

writer = csv.writer(f)
for val in list:
    writer.writerow([val])

However the output I get always has one row empty in between as follows.

cat

dog

duck

...

goat

I want to know how to make it correct as well as to have the list in the third column of csv.

1 Answers1

1

With Blanks

You can easily add empty columns by adding "None" entries in the list argument to writerow(). A fully working example follows:

import csv
import tempfile

list = ['cat', 'dog', 'duck', 'goat']

name = None
with tempfile.NamedTemporaryFile('w', delete=False) as f:
    writer = csv.writer(f)
    for val in list:
        writer.writerow([None, None, val])

    name = f.name

with open(name, 'r') as f:
    contents = f.read()
    print(contents)

The result is:

,,cat
,,dog
,,duck
,,goat

With Numbers

In order to have numbers starting from zero instead of blanks you can modify like so:

import csv
import tempfile

list = ['cat', 'dog', 'duck', 'goat']

name = None
with tempfile.NamedTemporaryFile('w', delete=False) as f:
    writer = csv.writer(f)
    pos = 0
    for val in list:
        writer.writerow([str(pos), str(pos+1), val])
        pos += 2

    name = f.name

with open(name, 'r') as f:
    contents = f.read()
    print(contents)
    print(dir(f))

This results in the following:

0,1,cat
2,3,dog
4,5,duck
6,7,goat
Dewald Abrie
  • 1,183
  • 7
  • 19