如何在CSV文件中编写UTF-8 [英] How to write UTF-8 in a CSV file

查看:223
本文介绍了如何在CSV文件中编写UTF-8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用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 转入

在您的代码中导入unicodecsv作为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.

这篇关于如何在CSV文件中编写UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆