0

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
3
  • use writer.writerows[row] Commented Jun 28, 2019 at 6:53
  • Still, its giving me the wrong output as below: Commented Jun 28, 2019 at 6:55
  • 1
    No need of iteration here. Use without for Commented Jun 28, 2019 at 6:58

2 Answers 2

2

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,
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

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='"') writer.writerow(row)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.