Reputation: 49
I wannted to extract some selected files from a sample.tar.gz files ( do not need to be extracted all the files inside sample.tar.gz files ) the file structures are looks like below.
sample.tar.gz is the base file, under this base file following files are contained.
hello_usb.tar.gz
hello_usb1.tar.gz
hello_usb2.tar.gz
world_usb1.tar.gz
world_usb2.tar.gz
world_usb3.tar.gz
I wanted to extract only "hello_*" files are to be extracted ( while extracting it should create a fiolder name same as the file name for example, while extracting hello_usb.tar.gz file it should create a folder name called as hello_usb.tar.gz/... )
I have tried with following codes but no luck.
tar = tarfile.open("D:\Python34\Testing\sample.tar.gz", "r:gz")
only_names = tar.getnames()
for count in range(len(only_names)):
print (only_names[count][:9])
if only_names[count][:9] == "hello_usb":
tar.extract(only_names[count], path = "D:\Python34\Testing")
#tar.extractfile(only_names[count])
Your help would be highly appreciated
Upvotes: 2
Views: 922
Reputation: 61235
Something like this may work.
import shutil
import glob
import os
with tarfile.open('D:\Python34\Testing\sample.tar.gz', 'r:gz') as tar:
tar.extractall()
os.chdir('sample')
for arch in glob.glob('hello_*'):
shutil.unpack_archive(arch, 'D:\Python34\Testing')
Upvotes: 1