写入csv文件时,rowrow失败并出现UnicodeEncodeError [英] when writing to csv file writerow fails with UnicodeEncodeError

查看:140
本文介绍了写入csv文件时,rowrow失败并出现UnicodeEncodeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一行:

c.writerow(new_values)

这会将多个值写入csv文件。通常,它工作正常,但有时会引发异常,并且不会在csv文件中写入该行。我不知道如何找出原因。

That writes a number of values to a csv file. Normally it is working fine but sometimes it throws an exception and doesn't write the line in the csv file. I have no idea how I can find out why.

这是我现在的异常处理:

This is my exception handling right now:

        try:
            c.writerow(new_values)
        except:
            print()
            print ("Write Error: ", new_values)

我评论了自己的例外情况,并说:

I commented out my own exception and it says:

    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u03b1' in position 14: character maps to <undefined>


推荐答案

好,我自己解决了这个问题:

Ok, I solved it by myself:

我只需要在csv.writer行中添加,encoding ='utf-8':

I just had to add ", encoding='utf-8'" to my csv.writer line:

c = csv.writer(open("Myfile.csv", 'w',  newline='', encoding='utf-8'))

这篇关于写入csv文件时,rowrow失败并出现UnicodeEncodeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆