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

2024-09-25 02:27:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码:

    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()

Tags: textinidtreeapplefortitleelement
1条回答
网友
1楼 · 发布于 2024-09-25 02:27:40

在写入文件之前,需要显式地对Unicode进行编码,否则Python将使用默认的ASCII编解码器为您进行编码。

选择一个编码并坚持它:

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

或者使用^{}创建一个在写入文件时为您编码的文件对象:

import io

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

您可能需要阅读:

在继续之前。

相关问题 更多 >