tags:

views:

124

answers:

3

When I try to write a field that includes whitespace in it, it gets split into multiple fields on the space. What's causing this? It's driving me insane. Thanks

data = open("file.csv", "wb")
w = csv.writer(data)
w.writerow(['word1', 'word2'])
w.writerow(['word 1', 'word2'])
data.close()

I'll get 2 fields(word1,word2) for first example and 3(word,1,word2) for the second.

+1  A: 

For me on Python 2.7, that gives:

word1,word2
word 1,word2

as expected.

Matthew Flaschen
+2  A: 

Not reproducible here:

>>> import csv
>>> data = open("file.csv", "wb")
>>> w = csv.writer(data)
>>> w.writerow(['word1', 'word2'])
>>> w.writerow(['word 1', 'word2'])
>>> data.close()
>>> 
[1]+  Stopped                 python2.6
$ cat file.csv
word1,word2
word 1,word2
$

What do you see when you do exactly this (or the window equivalent, control-Z to exit the interpreter where I did it to supend the intepreter and get a shell prompt)? What exact environment and version of Python?

Alex Martelli
That returns the expected results. I was opening the CSV in Openoffice, and that shows extra fields. Thanks. I guess I shouldn't rely on other programs when testing things. I'm on Ubuntu/Python 2.6.5.
matt
+4  A: 

The writing is correct, I think; the problem would be in reading. You never said what you're using to open such generated CSV. It might be splitting fields on comma or whitespace.

UPDATE: Try this, see if it helps:

w = csv.writer(data, quoting=csv.QUOTE_ALL)
Amadan
The problem was just me relying on Openoffice to check it. Thank you though.
matt