简体   繁体   English

写入CSV文件时如何解决编码问题

[英]How to fix encoding issue when writing to csv file

i have some encoding issuse when writing to csv file 写入csv文件时我有一些编码issuse

how can i fix it 我该如何解决

import csv


a = [s.encode('utf-8') for s in a]
f3 = open('test.csv', 'at')
writer = csv.writer(f3,delimiter = ',', lineterminator='\n',quoting=csv.QUOTE_ALL)
writer.writerow(a)

Error 错误

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    a = [s.encode('ascii') for s in a]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1: ordinal not in range(128)

How to make program work and write it to csv file? 如何使程序工作并将其写入csv文件?

I ran your code and it works without throwing any errors. 我运行了您的代码,它可以正常运行而不会引发任何错误。 Only thing is that your csv file contains byte encoded values. 唯一的问题是您的csv文件包含字节编码的值。 Values with ab' at the front. 前面带有ab'的值。 Is this what you were trying to accomplish? 这是您要完成的工作吗? I am using python 3.5.2 . 我正在使用python 3.5.2。

In the event you do not want byte encoded data just remove the 如果您不希望使用字节编码的数据,只需删除

a = [s.encode('utf-8') for s in a]

And it should work. 它应该工作。 Here is the output of your data into the csv when I ran it on my machine. 当我在计算机上运行数据时,这是将数据输出到csv中的结果。

http://puu.sh/r8ksr/d778437622.png http://puu.sh/r8ksr/d778437622.png

# encoding=utf8  
import sys  

reload(sys)  
sys.setdefaultencoding('utf8')

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

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