1

I'm trying to write into a string to csv file using csv modules. The string is getting printed in the excel sheet as single characters in different rows and not in one field.

with open('test.csv', 'w',newline='') as f:
    writer=csv.writer(f)
    writer.writerow("hello")
    writer.writerow("bye")

The output is like

 h     e     l      l     o         
 b     y     e      

What I simply want is

hello

bye

Also how do I write in a different column? there is no writecolumn() for it like writerow()

5
  • You have to give a list as the argument to .writerow(). Commented Jun 12, 2019 at 11:22
  • 1
    it treats the argument passed to it as an iterable so wrap your words in brackets to signify you want it as one column Commented Jun 12, 2019 at 11:23
  • writerow takes a sequence of elements, each written in its own column. Commented Jun 12, 2019 at 11:23
  • OK now I understand. I made a list of the strings and now they are properly displayed and also thanks for the column idea. Commented Jun 12, 2019 at 11:32
  • Try writer.writerow(["hello"]) Commented Jun 12, 2019 at 11:37

2 Answers 2

2

Adding to the previous answer,

If you want to do the same with csv.writerows() function:

rows = ["apple", "banana", "mango", "orange"]

with open('test.csv', 'w',newline='') as f:
    writer=csv.writer(f)
    writer.writerows([[row] for row in rows])

That should print all the rows, in 1 column per row.

Sign up to request clarification or add additional context in comments.

Comments

1

In order to output in two rows:

writer.writerow(["hello"])
writer.writerow(["bye"])

In order to output in two cols:

 writer.writerow(["hello","bye"])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.