在jupyter中解压缩.gz扩展文件

时间:2020-03-31 18:41:32

标签: python jupyter-notebook unzip

# Unzip the dataset (if we haven't already)
if not os.path.exists('./cola_public/'):
    !unzip cola_public_1.1.zip

以上代码将在jupyter笔记本中解压缩文件。 如果文件是.gz文件,我将如何以类似的方式进行操作?

2 个答案:

答案 0 :(得分:1)

zipfile软件包对于gzip来说效果很好

import zipfile as zf
file = zf.ZipFile("/path/to/file/YOUR_FILE.gzip")

答案 1 :(得分:0)

我假设您的文件是tar.gz,并且包含更多文件,则可以使用。 (您需要创建测试文件夹或使用root)

with tarfile.open('TEST.tar.gz', 'r:gz') as _tar:
    for member in _tar:
      if member.isdir():#here write your own code to make folders
         continue
      fname = member.name.rsplit('/',1)[1]
      _tar.makefile(member, 'TEST' + '/' + fname)

或者,如果您的gz不是tar文件,并且包含单个文件,则可以使用gzip 参考:-https://docs.python.org/2/library/gzip.html#examples-of-usage

import gzip
import shutil
def gunzip(file_path,output_path):
    with gzip.open(file_path,"rb") as f_in, open(output_path,"wb") as f_out:
        shutil.copyfileobj(f_in, f_out)
        f_in.close()
        f_out.close()

f='TEST.txt.gz'
gunzip(f,f.replace(".gz",""))
相关问题