代码之家  ›  专栏  ›  技术社区  ›  S Andrew

如何在python中提取gz文件

  •  1
  • S Andrew  · 技术社区  · 6 年前

    我有一个 .gz

    f = gzip.open(dest, 'rb')
    

    gz 广州 文件。

    这个问题已被标记为重复,我接受,但我还没有找到一个解决方案,我们可以真正下载文件,而不仅仅是阅读其内容。上述链接也是如此。

    2 回复  |  直到 6 年前
        1
  •  6
  •   norok2    4 年前

    你可以打开两个文件,从 gzipped

    import gzip
    
    def gunzip(source_filepath, dest_filepath, block_size=65536):
        with gzip.open(source_filepath, 'rb') as s_file, \
                open(dest_filepath, 'wb') as d_file:
            while True:
                block = s_file.read(block_size)
                if not block:
                    break
                else:
                    d_file.write(block)
    

    否则,你可以 shutil ,如中所示 How to unzip gz file using Python :

    import gzip
    import shutil
    
    def gunzip_shutil(source_filepath, dest_filepath, block_size=65536):
        with gzip.open(source_filepath, 'rb') as s_file, \
                open(dest_filepath, 'wb') as d_file:
            shutil.copyfileobj(s_file, d_file, block_size)
    

    %timeit gunzip(source_filepath, dest_filepath)
    # 129 ms ± 1.89 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
    %timeit gunzip_shutil(source_filepath, dest_filepath)
    # 132 ms ± 2.99 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
    
        2
  •  1
  •   S Andrew    6 年前

    我已经这样解决了这个问题:

    f = gzip.open(dest, 'r')
    file_content = f.read()
    file_content = file_content.decode('utf-8')
    f_out = open('file', 'w+')
    f_out.write(file_content)
    f.close()
    f_out.close()
    

    gz

    推荐文章