The csv module in Python doesn't work properly when there's UTF-8/Unicode involved. I have found, in the Python documentation and on other webpages, snippets that work for specific cases but you have to understand well what encoding you are handling and use the appropriate snippet.
How can I read and write both strings and Unicode strings from .csv files that "just works" in Python 2.6? Or is this a limitation of Python 2.6 that has no simple solution?
The wrapper
unicode_csv_reader
mentioned in the python documentation accepts Unicode strings. This is because csv does not accept Unicode strings. cvs is probably not aware of encoding or locale and just treats the strings it gets as bytes. So what happens is that the wrapper encodes the Unicode strings, meaning that it creates a string of bytes. Then, when the wrapper gives back the results from csv, it decodes the bytes again, meaning that it converts the UTF-8 bytes sequences to the correct unicode characters.If you give the wrapper a plain byte string e.g. by using
f.readlines()
it will give aUnicodeDecodeError
on bytes with value > 127. You would use the wrapper in case you have unicode strings in your program that are in the CSV format.I can imagine that the wrapper still has one limitation: since cvs does not accept unicode, and it also does not accept multi-byte delimiters, you can't parse files that have a unicode character as the delimiter.
A little late answer, but I have used unicodecsv with great success.
I confirm,
unicodecsv
is a great replacement for thecsv
module, I've just replacedcsv
byunicodecsv
in my source code, and it works like a charm.You should consider tablib, which has a completely different approach, but should be considered under the "just works" requirement.
Warning: tablib will reject your csv if it doesn't have the same number of items on every row.
Maybe this is blatantly obvious, but for sake of beginners I'll mention it.
In python 3.X
csv
module supports any encoding out of the box, so if you use this version you can stick to the standard module.For additional discussion please see: Does python 3.1.3 support unicode in csv module?
There is the usage of Unicode example already in that doc, why still need to find another one or re-invent the wheel?