【问题标题】:Reading through a bunch of .gz files error: Error -3 while decompressing: invalid code lengths set读取一堆 .gz 文件错误:解压缩时出现错误 -3:设置了无效的代码长度
【发布时间】:2017-02-26 20:23:10
【问题描述】:

我正在尝试通过使用 Python 2.7.10 中的多处理使用相同的函数来解析一堆 .gz json 文件(这些文件是文本文件)。然而,几乎在解析这些文件中每一行的最后,它会产生这个错误:

error: Error -3 while decompressing: invalid code lengths set

并停止执行。

这是我的代码:

import gzip
import json
from multiprocessing import Pool, cpu_count

def build_list(file_name):

    count = 0

    try:
        json_file = gzip.open(file_name, "r")
    except Exception as e:
        print e
    else:

        # Data parsing
        for line in json_file:
            try:
                row = json.loads(line)
            except Exception as e:
                print e
            else:                
                count += 1

if __name__ == "__main__":

    files = ["h1.json.gz", "h2.json.gz", "h3.json.gz", "h4.json.gz", "h5.json.gz"]

    pool = Pool(processes=cpu_count()-1)
    pool.map(build_list, files)

当我检查top 时,必须澄清程序开始运行良好并且文件是在每个处理器上分配的。我还使用gunzip -t 检查文件的完整性,它们似乎格式正确。我也没有看到在错误之前引发任何异常。您对我该如何解决有任何想法吗?提前致谢。

【问题讨论】:

  • 以二进制模式读取:gzip.open(..., "rb", ...)。我几乎肯定这是一个骗局,因为我发誓我几天前才看到这个解决方案,但我找不到问题。

标签: python json python-2.7 multiprocessing gzip


【解决方案1】:

以二进制方式读取:

gzip.open(file_name, "rb")

在某些平台上以文本模式阅读可能会破坏数据(因为它不是文本),并会导致诸如此类的奇怪错误。

【讨论】:

  • 感谢您的回复。我已经尝试过`gzip.open(file_name, "rb")`
【解决方案2】:

我最终使用了一个 try 块,它在读取时检查指针中每一行的完整性。所以最终的代码是这样的:

def build_list(file_name):

    count = 0

    try:
        json_file = gzip.open(file_name, "r")
    except Exception as e:
        print e
    else:

        try:
            # Data parsing
            for line in json_file:
                try:
                    row = json.loads(line)
                except Exception as e:
                    print e
                else:                
                    count += 1
        except Exception as e:
            print e

感谢您的所有 cmets。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-31
    • 2017-12-11
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    相关资源
    最近更新 更多