如何在CSV文件中写入UTF-8 [英] How to write UTF-8 in a CSV file
问题描述
我试图从一个PyQt4 QTableWidget
创建一个csv格式的文本文件。我想用UTF-8编码写文本,因为它包含特殊字符。我使用以下代码:
I am trying to create a text file in csv format out of a PyQt4 QTableWidget
. I want to write the text with a UTF-8 encoding because it contains special characters. I use following code:
import codecs
...
myfile = codecs.open(filename, 'w','utf-8')
...
f = result.table.item(i,c).text()
myfile.write(f+";")
它会工作,直到单元格包含特殊字符。我也尝试了
It works until the cell contains a special character. I tried also with
myfile = open(filename, 'w')
...
f = unicode(result.table.item(i,c).text(), "utf-8")
但是它也会在出现特殊字符时停止。我不知道我做错了什么。
But it also stops when a special character appears. I have no idea what I am doing wrong.
推荐答案
从您的shell运行:
From your shell run:
pip2 install unicodecsv
原始问题),假设您使用Python的内置 csv
模块,请切换
import csv
在您的代码中将
import unicodecsv as csv
。
And (unlike the original question) presuming you're using Python's built in csv
module, turn
import csv
into
import unicodecsv as csv
in your code.
是我的基础,我喜欢的答案,我可以直接使用,而不去另一个网站。我发现自己看着GitHub页第二次今天,从这个页面。因此这个答案。)
(Gijs' answer is the basis for this. I prefer answers that I can use directly without going to another website. I found myself looking at the GitHub page the second time today, coming from this page. Hence this answer.)
这篇关于如何在CSV文件中写入UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!