AlSub
AlSub

Reputation: 1155

How to output an specific csv format with open()?

I am trying to write a python list into a csv file by using csv and os library.

Here's what I got so far:

from os import path
import csv 
import os

example_list=[1,2,3,4,5]

file_path=path.relpath("path")

with open(file_path, mode='w') as f:
     list_writer = csv.writer(f, delimiter=',')
     for element in example_list:
        list_writer.writerow(element)

However when I open it in an excel workbook the output is writed as this (where each horizontal space represent a new cell):

# 1  2  3  4  5 

I've trying to get an expected output to look like this (where each vertical space represents a new cell):

# 1

# 2

# 3

# 4

# 5

How could I adjust this function in order to get desired output?

Upvotes: 0

Views: 292

Answers (2)

Midhilesh Momidi
Midhilesh Momidi

Reputation: 575

Your code gives the following error _csv.Error: iterable expected, not int because you need pass an iterable in writerow()

with open(path,'w',newline='') as f:
    list_writer = csv.writer(f, delimiter=',')
    for element in example_list:
        list_writer.writerow([element])

Here newline = '' avoids adding a space of extra row

Alternate way using writerows()

with open(path,'w',newline='') as f:
    list_writer = csv.writer(f, delimiter=',')
    list_writer.writerows([element] for element in example_list)

Upvotes: 0

joao
joao

Reputation: 2293

Your code produces the following error:

_csv.Error: iterable expected, not int

When writing the row, you should add brackets [] around the element to build a list (which is an iterable) :

list_writer.writerow([element])

You might as well replace the for loop with:

list_writer.writerow(example_list)

Upvotes: 1

Related Questions