【问题标题】:Encoding error - xlsxwriter - Python编码错误 - xlsxwriter - Python
【发布时间】:2014-10-22 07:45:05
【问题描述】:

我正在尝试从文件中拆分行并将它们放入 excel 文件 (xlsx) 中。根据 PS PAD,文件的编码是 'cp1250'。所以要在 xlsx 文件中包含正确的字符,我正在从 cp1250 - line = line.decode("cp1250") 解码这些行

问题是cca 3000 lines from 12000 返回这个错误:

'charmap' codec can't decode byte 0x81 in position 25: character maps to <undefined>

所以接下来我尝试解码(“utf-8”),我不知道为什么,但它更好。返回错误的只有 330 行:

'utf8' codec can't decode byte 0x8e in position 0: invalid start byte

你们知道我做错了什么吗?

编辑:错误大多发生在包含“Ž”或“Š”的行

这里是代码:(在py文件的顶部我放了“# -- coding: utf-8 --”)

def toXls(file):
workbook = xlsxwriter.Workbook(file)
worksheet = workbook.add_worksheet()
a=0
with open("filtrovane.txt") as f:
    x=0
    for line in f:

        try:
            line = line[:-1].decode("utf-8") """It should be "cp1250" according to PSPAD editor"""
            # line = line.encode("ISO 8859-2")
            splitted = line.split("::")

            if len(splitted)==7:
                try:
                    a=a+1
                    worksheet.write(a,0,splitted[0])
                    worksheet.write(a,1,splitted[1])
                    worksheet.write(a,2,splitted[2])
                    worksheet.write(a,3,splitted[3])
                    worksheet.write(a,4,splitted[4])
                    worksheet.write(a,5,splitted[5])
                    worksheet.write(a,6,splitted[6])
                except Exception as e:
                    print "!!"+line+" "+a + e
        except Exception as e:
            print e
            x=x+1
print x
workbook.close()

【问题讨论】:

  • 当您尝试将其保存到文本文件时会发生什么情况,是否会出现同样的问题?

标签: python excel encoding utf-8 xlsxwriter


【解决方案1】:

XlsxWriter docs/repo 中有两个示例说明如何读取 UTF-8Shift JIS 文件并将它们转换为 xlsx 文件。

cp1250 应该同样有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-04
    • 2019-01-18
    • 2011-03-14
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多