开发者

Writing white space to CSV fields in Python?

开发者 https://www.devze.com 2022-12-31 21:52 出处:网络
When I try to write a field that includes whitespace in it, it g开发者_JAVA百科ets split into multiple fields on the space. What\'s causing this? It\'s driving me insane. Thanks

When I try to write a field that includes whitespace in it, it g开发者_JAVA百科ets 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.


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)


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?


For me on Python 2.7, that gives:

word1,word2
word 1,word2

as expected.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号