UnicodeEncodeError: 'ascii'编解码器无法在第7个位置上编码字符u'\xe9',因为它不在128个字符的范围内。

38

我有这段代码:

    printinfo = title + "\t" + old_vendor_id + "\t" + apple_id + '\n'
    # Write file
    f.write (printinfo + '\n')

但是当我运行它时,出现了以下错误:
    f.write(printinfo + '\n')
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

我在写这个时遇到了麻烦:

Identité secrète (Abduction) [VF]

任何建议,请,不确定如何解决。
感谢。
更新: 这是我的大部分代码,您可以看到我正在做什么:
def runLookupEdit(self, event):
    newpath1 = pathindir + "/"
    errorFileOut = newpath1 + "REPORT.csv"
    f = open(errorFileOut, 'w')

global old_vendor_id

for old_vendor_id in vendorIdsIn.splitlines():
    writeErrorFile = 0
    from lxml import etree
    parser = etree.XMLParser(remove_blank_text=True) # makes pretty print work

    path1 = os.path.join(pathindir, old_vendor_id)
    path2 = path1 + ".itmsp"
    path3 = os.path.join(path2, 'metadata.xml')

    # Open and parse the xml file
    cantFindError = 0
    try:
        with open(path3): pass
    except IOError:
        cantFindError = 1
        errorMessage = old_vendor_id
        self.Error(errorMessage)
        break
    tree = etree.parse(path3, parser)
    root = tree.getroot()

    for element in tree.xpath('//video/title'):
        title = element.text
        while '\n' in title:
            title= title.replace('\n', ' ')
        while '\t' in title:
            title = title.replace('\t', ' ')
        while '  ' in title:
            title = title.replace('  ', ' ')
        title = title.strip()
        element.text = title
    print title

#########################################
######## REMOVE UNWANTED TAGS ########
#########################################

    # Remove the comment tags
    comments = tree.xpath('//comment()')
    q = 1
    for c in comments:
        p = c.getparent()
        if q == 3:
            apple_id = c.text
        p.remove(c)
        q = q+1

    apple_id = apple_id.split(':',1)[1]
    apple_id = apple_id.strip()
    printinfo = title + "\t" + old_vendor_id + "\t" + apple_id

    # Write file
    # f.write (printinfo + '\n')
    f.write(printinfo.encode('utf8') + '\n')
f.close()

6
如果你看一下问题右边,你会注意到一个“相关问题”的栏目。我建议你从那里开始查找。当你写下问题标题时,系统也会给出可能是重复的列表。 - Some programmer dude
@MartijnPieters:像往常一样,你是正确的。评论已删除。 - cdarke
1个回答

73

在将内容写入文件之前,您需要明确地对Unicode进行编码,否则Python会使用默认的ASCII编解码器为您执行此操作。

选择一个编码并坚持使用它:

f.write(printinfo.encode('utf8') + '\n')

或使用io.open()创建一个文件对象,当您写入文件时,它会为您进行编码:

import io

f = io.open(filename, 'w', encoding='utf8')

在继续之前,您可能需要阅读:


使用 f.write(printinfo.encode('utf8') + '\n') 可以工作,但会创建奇怪的字符 Identit√© secr√®te (Abduction) [VF],应该是带重音符号的 Identité secrète (Abduction) [VF]。 - speedyrazor
@Martin Pieters:我已经仔细阅读了,但是并不真正理解。如果我在读取的XML文件中有“Identité secrète”,我会挑选出这些行并将它们写入文件,但是该行会变成“Identit√© secr√®te”。很抱歉要问,但请问有哪些代码可以解决这个问题? - speedyrazor
@speedyrazor:你的XML文件也使用了编解码器。它可能使用UTF-8,或者在XML文件的第一行指定了不同的编解码器。然后XML解析器将该数据解码为Unicode值。当将值写入文件时,您需要再次选择编解码器以写入字节。我为您选择了UTF-8,因为该编解码器可以编码所有Unicode字符,但是您用于查看结果文件的任何内容都使用了不同的编解码器来解释这些字节。 é 字符是Unicode代码点U+00E9。UTF-8将其编码为两个字节,十六进制C3和A9。错误解释这两个字节会给您带来 √© - Martijn Pieters
@speedyrazor:如果我不知道你是如何再次读取生成的文件的,我无法为你提供进一步的帮助。 - Martijn Pieters
@speedyrazor:我并没有问你是如何生成Unicode值的,我问的是你是如何读取脚本写入的文件的。 - Martijn Pieters
显示剩余10条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接