Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

python - How to extract the content of `*.tar.gz` dynamically

I have quite big *.tar.gz file (10Gb) that contains individuals files (no sub-folders). In Jupyter Notebook it takes several hours to untar this archive. Once all files are extracted, I need to upload them into a storage location.

This is what I currently have:

untar = tarfile.TarFile(tarfilename)
untar.extractall()
untar.close()

Is it possible to extract the content of *.tar.gz dynamically (i.e. continuously)? Something like this:

with open(tarfilename, "r") as tararchive:
   for eachfile in tararchive:
       save_to_storage_location(eachfile)

So, instead of waiting until the tar archive is untarred, I just want to "open" it and move all the content one by one into the storage location.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A little of tinkering with the package has shown me you can list all the files under the tar file and you could extract them individually. Without more information on what you want to do with the files afterwards (i.e. where or how you want to upload them) I cannot help on that end.

You can cycle through your files like so:

import tarfile

with tarfile.open("path/to/file.tar.gz", "r") as file:
    for each in file.getnames():
        print(each)
        file.extract(each)

At the last stage the individual file has been extracted and will be sitting in your current working directory, you can hence do something with it


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...