Sergey
Sergey

Reputation: 167

how to write a string to csv?

help please write data horizontally in csv-file.

the following code writes this:

import csv
with open('some.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows('jgjh')

but I need so

Upvotes: 0

Views: 126

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124928

The csv module deals in sequences; use writer.writerow() (singular) and give it a list of one column:

writer.writerow(['jgjh'])

The .writerow() method will take each element in the sequence you give it and make it one column. Best to give it a list of columns, and ['jgjh'] makes one such column.

.writerows() (plural) expects a sequence of such rows; for your example you'd have to wrap the one row into another list to make it a series of rows, so writer.writerows([['jgjh']]) would also achieve what you want.

Upvotes: 4

Related Questions