【问题标题】:gzip with file descriptor带有文件描述符的 gzip
【发布时间】:2015-11-25 21:15:42
【问题描述】:

我需要能够使用文件描述符打开压缩后的 CSV 文件。当我执行以下操作时(这是仍然触发错误的简化代码):

file_path = r"E39O6KS6J8MIZW.00.0f6db4e5.gz"
fd = os.open(file_path, os.O_RDONLY, os.O_BINARY)
# ...
file_object = gzip.GzipFile(fileobj=io.FileIO(fd, mode='rb'))
reader = csv.reader(io.BufferedReader(file_object))
for row in reader:
    print row

我收到一个 CRC 校验错误:

Traceback (most recent call last):
  File "./log_processing_scripts/dev.py", line 40, in <module>
    post()
  File "./log_processing_scripts/dev.py", line 36, in post
    for row in reader:
  File "C:\Python27\lib\gzip.py", line 252, in read
    self._read(readsize)
  File "C:\Python27\lib\gzip.py", line 299, in _read
    self._read_eof()
  File "C:\Python27\lib\gzip.py", line 338, in _read_eof
    hex(self.crc)))
IOError: CRC check failed 0x4b77635f != 0xbe13716L

文件没有(!)损坏,我可以使用 gzip.open(file_path)处理它。

我错过了什么?

【问题讨论】:

    标签: python python-2.7 file-io gzip


    【解决方案1】:

    O_RDONLY 和 O_BINARY 标志应该是 or'd 在一起,像这样:

    fd = os.open(file_path, os.O_RDONLY | os.O_BINARY)
    

    参考:https://docs.python.org/2/library/os.html#open-constants

    【讨论】:

    • 啊,废话!知道这是一件非常愚蠢的事情。谢谢。
    • 很好发现,赞成。看着 GzipFile 的帮助,我注意到 fileobj, which can be a regular file, a StringIO object, or any other object which simulates a file 所以我认为os.open 返回的低级文件描述符(一个 int)可能不匹配/工作
    • @Pynchia:这就是我将 fd 包装在 FileIO 中的原因
    • 是的,当然,抱歉。你也可以使用os.fdopen
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 2019-06-11
    • 1970-01-01
    • 2012-11-27
    相关资源
    最近更新 更多