python csv编码writerow

Yeb*_*ach 0 python csv encoding

在Windows 2008服务器上使用web2py我有以下问题

我正在从json创建csv文档,当写入列表到文件时,我得到以下错误.它在csv writerow上崩溃了

<type 'exceptions.UnicodeEncodeError'> 'ascii' codec can't encode character u'\\u010c'
Run Code Online (Sandbox Code Playgroud)

它在我的电脑上运行正常.Windows 7但在服务器上我有编码问题

有什么建议?谢谢

我创建文件的代码如下

dataDict = json.loads(data.replace("'", "\""))
path = path
scriptName = os.path.join(path, id + 'script.txt')
file = open(scriptName, 'wb') 
output = csv.writer(file, delimiter='\t')

##Month hours
file.write("begin month_hours \r\n")
file.write("delavec    mesec    month_hours_min    month_hours_max\r\n")
for rec in dataDict["mandatory"]:
    output.writerow(rec)
file.write("\r\nend month_hours \r\n")
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

JSON字符串始终是Unicode值,在Python 2中需要在写入CSV文件时进行编码.如果您不明确地这样做,Python将使用ASCII编解码器.如果所有数据都包含ASCII范围内的文本,但是当遇到超出该范围的数据时失败,那就没问题.

选择不同的编码并明确编码; UTF-8是一个很好的编码选择:

for rec in dataDict["mandatory"]:
    output.writerow([unicode(c).encode('utf8') for c in rec])
Run Code Online (Sandbox Code Playgroud)

我首先将所有值转换为unicode(),以防你有数据,那里还没有unicode()值; 数字或布尔值或None例如.然后将结果显式编码为UTF-8.

  • @Wes:在Python 3中,您会以文本模式打开文件并指定编解码器,因此整个问题甚至不会播放。您根本不需要对传递给“csv.writer()”对象的数据进行编码。 (2认同)