0

I want to create new csv file and write some string in it:

with open('results.csv', 'w') as resultsfile:
    csv_writer = csv.writer(resultsfile)
    csv_writer.writerow('mystring')

Output

m,y,s,t,r,i,n,g

The thing here that the default delimiter is comma and there no way to use this:

csv_writer = csv.writer(resultsfile, delimiter='')

So how can I write my string without any delimiter inside the csv file?

Sheldore
  • 37,862
  • 7
  • 57
  • 71
danny kob
  • 171
  • 1
  • 2
  • 12

1 Answers1

2

You are calling .writerow(). This method expects a list (i.e. columns), but you only give it one single string.

Give it a list of columns. If you have only one column, you still need to give it a list.

csv_writer.writerow(['mystring'])

Strings are also lists (of letters), which explains the behavior you see when you do this:

csv_writer.writerow('mystring')
Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • It expects *an iterable*, not a list. – juanpa.arrivillaga Sep 20 '18 at 15:56
  • @juanpa.arrivillaga I know, but I kept the jargon down for the OP's sake. – Tomalak Sep 20 '18 at 15:57
  • It's not a mere issue of jargon, for example, if it expects a list, then why did it happily take a string? – juanpa.arrivillaga Sep 20 '18 at 16:00
  • I explained that. I'm all for using the right terminology, but given the OP's level of understanding, I don't think that it's particularly helpful to throw around words like "iterable". They just want to know why the csv writer does what it does, at a conceptional level. And the conceptional level is "they passed in one item where they should have been passing a list of items" (or "a list of one item", as it were). They'll get round to understanding what an iterable is soon enough, I'm sure. – Tomalak Sep 20 '18 at 16:05