在Python中使用GZIP模块

use*_*358 23 python gzip

我正在尝试使用Python GZIP模块来简单地解压缩目录中的几个.gz文件.请注意,我不想读取文件,只能解压缩它们.搜索这个网站一段时间后,我有这个代码段,但它不起作用:

import gzip
import glob
import os
for file in glob.glob(PATH_TO_FILE + "/*.gz"):
    #print file
    if os.path.isdir(file) == False:
        shutil.copy(file, FILE_DIR)
        # uncompress the file
        inF = gzip.open(file, 'rb')
        s = inF.read()
        inF.close()
Run Code Online (Sandbox Code Playgroud)

.gz文件位于正确的位置,我可以使用print命令打印完整路径+文件名,但GZIP模块没有正确执行.我错过了什么?

gon*_*opp 40

如果没有错误,gzip的模块可能被正确执行.

我不想读取文件,只解压缩它们

gzip模块不能像7-zip那样用作桌面存档程序 - 如果不"读取"文件,就无法"解压缩"文件.从编程的角度来看,"解压缩"可能意味着更准确地描述为"从压缩文件读取流并将其写入新文件".

inF = gzip.open(file, 'rb')
s = inF.read()
inF.close()
Run Code Online (Sandbox Code Playgroud)

在这里,你只是阅读流.您只需将其写入新文件:

with open(out_filename, 'wb') as out_file:
    out_file.write(s)
Run Code Online (Sandbox Code Playgroud)

  • @ user3111358我想说的是"解压缩"在不同的环境中意味着不同的东西.我敢打赌,如果你问几个人在这里读过你的代码,他们会告诉你文件**是未被压缩的.因此,我必须问:你怎么知道**文件没有"未压缩"?是因为在运行代码时,没有新文件与压缩文件放在同一目录中? (3认同)

Mar*_*oma 6

您应该使用with打开文件,当然,存储读取压缩文件的结果.见gzip文档:

import gzip
import glob
import os
import os.path

for gzip_path in glob.glob("%s/*.gz" % PATH_TO_FILE):
    if not os.path.isdir(gzip_path):
        with gzip.open(gzip_path, 'rb') as in_file:
            s = in_file.read()

        # Now store the uncompressed data
        path_to_store = gzip_fname[:-3]  # remove the '.gz' from the filename

        # store uncompressed file data from 's' variable
        with open(path_to_store, 'w') as f:
            f.write(s)
Run Code Online (Sandbox Code Playgroud)

根据您想要做什么,您可能需要查看tarfile'r:gz'选择打开文件.


Jan*_*rny 5

您正在将文件解压缩为s变量,并且不对其执行任何操作.你应该停止搜索stackoverflow并阅读至少python教程.认真.

无论如何,你的代码有几个问题:

  1. 你需要的是将解压缩的数据存储s到某个文件中.

  2. 没有必要复制实际*.gz文件.因为在您的代码中,您正在解压缩原始gzip文件而不是副本.

  3. 你正在使用file,这是一个保留字,作为一个变量.这不是一个错误,只是一个非常糟糕的做法.

这可能应该做你想要的:

import gzip
import glob
import os
import os.path

for gzip_path in glob.glob(PATH_TO_FILE + "/*.gz"):
    if os.path.isdir(gzip_path) == False:
        inF = gzip.open(gzip_path, 'rb')
        # uncompress the gzip_path INTO THE 's' variable
        s = inF.read()
        inF.close()

        # get gzip filename (without directories)
        gzip_fname = os.path.basename(gzip_path)
        # get original filename (remove 3 characters from the end: ".gz")
        fname = gzip_fname[:-3]
        uncompressed_path = os.path.join(FILE_DIR, fname)

        # store uncompressed file data from 's' variable
        open(uncompressed_path, 'w').write(s)
Run Code Online (Sandbox Code Playgroud)