繁体   English   中英

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

[英]How to write UTF-8 in a CSV file

我正在尝试从 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,请看这里

从你的 shell 运行:

pip2 install unicodecsv

并且(与原始问题不同)假设您使用的是 Python 的内置csv模块,转
import csv导入
在您的代码import unicodecsv as csv

使用这个包,它就可以工作: https ://github.com/jdunck/python-unicodecsv。

对我来说,Python 2 CSV 模块文档中的UnicodeWriter类并没有真正起作用,因为它破坏了csv.writer.write_row()接口。

例如:

csv_writer = csv.writer(csv_file)
row = ['The meaning', 42]
csv_writer.writerow(row)

有效,同时:

csv_writer = UnicodeWriter(csv_file)
row = ['The meaning', 42]
csv_writer.writerow(row)

将抛出AttributeError: 'int' object has no attribute 'encode'

由于UnicodeWriter显然希望所有列值都是字符串,我们可以自己转换值并使用默认的 CSV 模块:

def to_utf8(lst):
    return [unicode(elem).encode('utf-8') for elem in lst]

...
csv_writer.writerow(to_utf8(row))

或者我们甚至可以猴子补丁 csv_writer 添加一个write_utf8_row函数 - 练习留给读者。

Python 文档中的示例展示了如何编写 Unicode CSV 文件: http ://docs.python.org/2/library/csv.html#examples

(这里不能复制代码,因为它受版权保护)

对于python2 ,您可以在csv_writer.writerows(rows)之前使用此代码
此代码不会将整数转换为 utf-8 字符串

def encode_rows_to_utf8(rows):
    encoded_rows = []
    for row in rows:
        encoded_row = []
        for value in row:
            if isinstance(value, basestring):
                value = unicode(value).encode("utf-8")
            encoded_row.append(value)
        encoded_rows.append(encoded_row)
    return encoded_rows
["

try:
    csv.writer(open(os.devnull, 'w')).writerow([u'\u03bc'])
    PREPROCESS = lambda array: array
except UnicodeEncodeError:
    logging.warning('csv module cannot handle unicode, patching...')
    PREPROCESS = lambda array: [
        item.encode('utf8')
        if hasattr(item, 'encode') else item
        for item in array
    ]

一个非常简单的技巧是使用 json 导入而不是 csv。 例如,而不是 csv.writer 只需执行以下操作:

    fd = codecs.open(tempfilename, 'wb', 'utf-8')  
    for c in whatever :
        fd.write( json.dumps(c) [1:-1] )   # json dumps writes ["a",..]
        fd.write('\n')
    fd.close()

基本上,给定正确顺序的字段列表,json 格式的字符串与 csv 行相同,除了分别位于开头和结尾的 [ 和 ] 。 json 似乎对 python 2 中的 utf-8 很健壮。 *

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM