Python 2.7 ';ascii';编解码器可以';t编码字符x
我正在尝试将一些特殊字符写入.csv文件。我的代码在这里:Python 2.7 ';ascii';编解码器可以';t编码字符x,python-2.7,csv,character-encoding,decoding,Python 2.7,Csv,Character Encoding,Decoding,我正在尝试将一些特殊字符写入.csv文件。我的代码在这里: fp = open(csv_file, 'w') test = [] test.append(unicode('òHeyàù', 'utf-8')) fp.write('\t'.join(test[0].encode('UTF-8'))) fp.write('\n') 这是输出: 嘿,嘿 我想应该解码。然后我写了这个: test = [] test.append('òHeyàù'.encode('utf-8')) fp.write('
fp = open(csv_file, 'w')
test = []
test.append(unicode('òHeyàù', 'utf-8'))
fp.write('\t'.join(test[0].encode('UTF-8')))
fp.write('\n')
这是输出:
嘿,嘿
我想应该解码。然后我写了这个:
test = []
test.append('òHeyàù'.encode('utf-8'))
fp.write('\t'.join(test[0].decode('UTF-8')))
fp.write('\n')
出现以下错误:
UnicodeDecodeError:“ascii”编解码器无法解码位置中的字节0xc3
0:序号不在范围内(128)
如何将特定字符写入CSV文件
编辑:
我尝试将字符串转换为ascii,但仍然无法正常工作:
test = []
test.append(unicode('òHeyàù', 'utf-8'))
testtest = test[0].encode('UTF-8')
swriter = csv.writer(fp, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
swriter.writerow([ord(c) for c in testtest]) # converting string to ascii however it prints a list of numbers
为什么
在最后一次写入时决定?您正在编写,因此需要进行编码。在任何情况下,您都在使用字符串(而不是unicode字符串),因为'\t'
是一个字符串。保留字符串ASCII(因此不带重音)。更好的方法是:使用python3,它纠正了(而不是添加hack)字符串的编码/解码。post已经过编辑。您已经指出了使使用ASCII变得不可能的要求。