gpt4 book ai didi

python - 如何在 CSV 文件中写入 UTF-8

转载 作者:IT老高 更新时间:2023-10-28 21:33:46 25 4
gpt4 key购买 nike

我正在尝试从 PyQt4 QTableWidget 创建一个 csv 格式的文本文件。我想用 UTF-8 编码编写文本,因为它包含特殊字符。我使用以下代码:

import codecs
...
myfile = codecs.open(filename, 'w','utf-8')
...
f = result.table.item(i,c).text()
myfile.write(f+";")

它一直有效,直到单元格包含特殊字符。我也试过了

myfile = open(filename, 'w')
...
f = unicode(result.table.item(i,c).text(), "utf-8")

但是当出现特殊字符时它也会停止。我不知道我做错了什么。

最佳答案

对于 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,查看 here .

关于python - 如何在 CSV 文件中写入 UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18766955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com