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


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

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

zipfile包在gzip 上运行得很好

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

我假设您的文件是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-使用

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",""))

最新更新