Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中处理unicode字符的问题_Python_Unicode - Fatal编程技术网

python中处理unicode字符的问题

python中处理unicode字符的问题,python,unicode,Python,Unicode,我编写了以下代码,用于将内容写入文件 with codecs.open(name,"a","utf8") as myfile: myfile.write(str(eachrecord[1]).encode('utf8')) myfile.write(" ") myfile.write(str(eachrecord[0]).encode('utf8')) myfile.write("\n")` 上面的代码在编写uni代

我编写了以下代码,用于将内容写入文件

   with codecs.open(name,"a","utf8") as myfile:
         myfile.write(str(eachrecord[1]).encode('utf8'))
         myfile.write(" ")
         myfile.write(str(eachrecord[0]).encode('utf8'))
         myfile.write("\n")`
上面的代码在编写uni代码字符时无法正常工作……即使我正在使用编解码器并进行编码。我一直在犯错误

UnicodeEncodeError:“ascii”编解码器无法对位置6中的字符u'\xe1'进行编码:序号不在范围内(128)

有人能看出我哪里做错了吗

编辑:

with codecs.open(name,"a","utf8") as myfile:
                    myfile.write(unicode(eachrecord[1]))
                    myfile.write(" ")
                    myfile.write(unicode(eachrecord[0]))
                    myfile.write("\n")

这很有效。感谢所有的快速评论和回答。这真的很有帮助。直到你们告诉我删除
str()
调用,我才意识到python有“unicode”选项。他们正在使用默认编码进行隐式编码(
ascii

什么类型的
eachrecord[1]
str
造成了混乱,我想,用
unicode
来代替。我想你甚至不必对unicode字符串进行编码,因为使用编解码器打开的文件应该可以处理它。每条记录[1]可以是字符串或数字类型错误:强制使用unicode:需要字符串或缓冲区,int-find..关于如何解决这个问题的任何建议谢谢,当我删除str()调用时,我一直遇到这样的错误“AttributeError:'int'对象没有属性'encode'”