Alex Rivera | Logout

Python: Extract using tarfile but ignoring directories

Asked 2011-12-06T19:48:13.087
24

If I have a .tar file with a file '/path/to/file.txt', is there a way (in Python) to extract the file to a specified directory without recreating the directory '/path/to'?

Edit
Report

1 Answer

32

I meet this problem as well, and list the complete example based on ekhumoro's answer

import os, tarfile
output_dir = "."
tar = tarfile.open(tar_file)
for member in tar.getmembers():
  if member.isreg():  # skip if the TarInfo is not files
    member.name = os.path.basename(member.name) # remove the path by reset it
    tar.extract(member,output_dir) # extract 
answered 2013-05-09T01:36:01.347

Your Answer