1

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.

3 Answers 3

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

The problem was just me relying on Openoffice to check it. Thank you though.
3

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?

1 Comment

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.
1

For me on Python 2.7, that gives:

word1,word2
word 1,word2

as expected.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.