sairanga talari
sairanga talari

Reputation: 57

Write a list of values as separate columns to a CSV file using Python

I am trying to write the elements of a list (each time I get from a for loop) as individual columns to a CSV file. But the elements are adding as an individual rows, but not columns.

I am new to python. What needs to be changed in my code? Please tell me

import csv
row=['ABC','XYZ','','','ABCD','']  #my list looks like this every time
with open('some.csv', 'w') as writeFile:
    writer = csv.writer(writeFile, delimiter=',', quotechar='"')
    for item in row:
        writer.writerow([item])

But I am getting the output as below:

ABC

XYZ

ABCD

My expected output is a below:

ABC XYZ    ABCD

Upvotes: 0

Views: 1283

Answers (2)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

You are iterating over the list row and writing each element as a new row in your code when you do writer.writerow([item]).

Instead you want to write the entire row in one line using writer.writerow

import csv

row=['ABC','XYZ','','','ABCD','']  #my list looks like this every time

with open('some.csv', 'w') as writeFile:

    writer = csv.writer(writeFile, delimiter=',', quotechar='"')
    #Write the list in one row
    writer.writerow(row)

The file will look like

ABC,XYZ,,,ABCD,

Upvotes: 2

kuldeep rawani
kuldeep rawani

Reputation: 54

Actually you are writing in different rows, you don't need to do that. You can write your whole list as a single row. You need spaces so for that you can modify your list.

Upvotes: 1

Related Questions