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

问题描述 投票:0回答:2
# Unzip the dataset (if we haven't already)
if not os.path.exists('./cola_public/'):
    !unzip cola_public_1.1.zip

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

python jupyter-notebook unzip
2个回答
0
投票

zipfile软件包对于gzip非常有效

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

0
投票

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

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",""))
© www.soinside.com 2019 - 2024. All rights reserved.