将俄语符号写入csv时出现Unicode错误

sqxo8psd  于 2023-06-03  发布在  其他
关注(0)|答案(4)|浏览(482)

我想写西里尔符号到csv文件,但我得到unicode编码错误。英语符号工作完美。我用的是Python 3.6.2。
UnicodeEncodeError:“ascii”编解码器无法对位置1-6中的字符进行编码:序号不在范围内(128)

import csv

with open("test.csv", 'w') as csvfile:
    csvfile = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    hello = 'привет, мир!'
    csvfile.writerow([hello])
kuarbcqp

kuarbcqp1#

打开文件时声明文件的编码。根据csv文档,newline=''也是必需的。

import csv

with open('test.csv','w',encoding='utf8',newline='') as csvfile:
    csvfile = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    hello = 'привет, мир!'
    csvfile.writerow([hello])
ma8fv8wu

ma8fv8wu2#

您只需要在将hello字符串写入文件(csv)之前对其进行编码。否则Python只要求你输入ascii字符,如果是非ascii字符,你可以使用utf-8编码:

# -*- coding: utf-8 -*-
import csv

with open("test.csv", 'w') as csvfile:
    csvfile = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    hello = u'привет, мир!' # Better way of declaring a unicode string literal
    csvfile.writerow([hello.encode("utf-8")])
xqnpmsa8

xqnpmsa83#

将此代码添加到文件中

# encoding=utf8  
   --------------------------------------
   import sys  
   reload(sys)  
   sys.setdefaultencoding('utf8')
qxsslcnc

qxsslcnc4#

对于使用Python 2的人,使用这个函数而不是普通的“open”函数:

import codecs
codecs.open(out_path, encoding='utf-8', mode='w')

这相当于Python 3中的以下内容:

open(out_path, 'w', encoding='utf8')

相关问题