【问题标题】:Python Throwing "'utf8' codec can't decode byte 0xd0 in position 0" ErrorPython抛出“'utf8'编解码器无法解码位置0中的字节0xd0”错误
【发布时间】:2013-10-01 13:44:45
【问题描述】:

我正在尝试加载当前存在的工作表并导入如下所示的文本文件(逗号分隔值)屏幕截图,

Excel表格:

文本文件:

我正在使用如下所示的代码:

# importing necessary modules for performing the required operation
    import glob
    import csv
    from openpyxl import load_workbook
    import xlwt

    #read the text file(s) using the CSV modules and read the dilimiters and quoutechar
    for filename in glob.glob("E:\Scripting_Test\Phase1\*.txt"):
        spamReader = csv.reader((open(filename, 'rb')), delimiter=',')


        #read the excel file and using xlwt modules and set the active sheet
        wb = load_workbook(filename=r"E:\Scripting_Test\SeqTem\Seq0001.xls")
        ws = wb.worksheets(0)


        #write the data that is in text file to excel file
        for rowx, row in enumerate(spamReader):
            for colx, value in enumerate(row):
                ws.write(rowx, colx, value)

        wb.save()

我收到以下错误消息:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xd0 in position 0: invalid continuation byte

还有一个问题:如何告诉python从excel表格的A3列开始导入文本数据?

【问题讨论】:

    标签: excel python-2.7 text openpyxl


    【解决方案1】:

    Unicode 编码让我感到困惑,但你不能通过以下方式强制该值忽略无效字节:

    value = unicode(value, errors='ignore')
    

    这里是更多阅读 unicode 的好答案:unicode().decode('utf-8', 'ignore') raising UnicodeEncodeError

    【讨论】:

    • 谢谢你,亚当!我试着这样做,但仍然是同样的错误。
    【解决方案2】:

    openpyxl 只处理OOXML 格式(xlsx/xlsm)。 请尝试使用 Excel 保存为 xlsx 文件格式而不是 xls。

    如果要将 xls 文件转换为代码中的 xlsx。请尝试以下列表中的一个选项:

    1. 在 Windows 中,您还可以使用excelcnv 工具将 xls 转换为 xlxx。
    2. 在 Linux 中,请查看this article。
    3. 或者,您可以在 Python 中使用 xlrd 转换为 xlsx。请查看this Q&A。

    【讨论】:

      【解决方案3】:

      您好,您确定没有包含UTF-8 BOM 的文档

      您可以尝试使用UTF-8 BOM codec。一般Windows+UTF+8会有点麻烦。虽然它显示的那个字符可能不是 BOM。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-09
        • 2020-09-20
        • 2015-02-23
        • 2011-06-27
        • 2017-05-19
        • 1970-01-01
        • 1970-01-01
        • 2014-07-09
        相关资源
        最近更新 更多