简体   繁体   中英

Writing white space to CSV fields in Python?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM