如何在 CSV 文件中写入 UTF-8 [英] How to write UTF-8 in a CSV file
本文介绍了如何在 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.
推荐答案
Python 3.x 非常简单 (文档).
It's very simple for Python 3.x (docs).
import csv
with open('output_file_name', 'w', newline='', encoding='utf-8') as csv_file:
writer = csv.writer(csv_file, delimiter=';')
writer.writerow('my_utf8_string')
对于 Python 2.x,请查看此处.
For Python 2.x, look here.
这篇关于如何在 CSV 文件中写入 UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文