Quantico Quantico -4 years ago 143
Python Question

Writing to csv breaks string to characters

I am trying to write into a csv file, I have a hard coded header that I want to write:

head = ["Q151", "item time", "deliberativness", "deliberativness time",
"Q153", "item time", "deliberativness", "deliberativness time"]


But when I run the csv writer it is inserting every char into a different column, and every item in the list to a different row. so I am getting

Q 1 5 1
i t e m t i m e


and not
Q151 item time ...


with open('some.csv', 'wb') as f:
writer = csv.writer(f)
for r in head:
writer.writerow(r)


I am using a simple
writer
like in the python docs. What am I doing wrong?

excepted result as I said above Q151 item time ...

Answer Source

You could use this code

with open('some.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerow(first_row)

Writer iterate your variable and write each element to the next cell. When you give it string value, writer iterate it. So to write all the lines you could add a loop.

with open('some.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerow(first_row)
    list_of_rows = [['1', '2', '3'], ]
    for row in list_of_rows:
         writer.writerow(row)
    # but better to use writerows
    writer.writerows(list_of_rows)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download