Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Extract using tarfile but ignoring directories

Tags:

python

tar

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'?

like image 822
meteoritepanama Avatar asked Dec 06 '11 19:12

meteoritepanama


2 Answers

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 
like image 116
Larry Cai Avatar answered Sep 28 '22 05:09

Larry Cai


The data attributes of a TarInfo object are writable. So just change the name to whatever you want and then extract it:

import sys, os, tarfile

args = sys.argv[1:]
tar = tarfile.open(args[0])
member = tar.getmember(args[1])
member.name = os.path.basename(member.name)
path = args[2] if len(args) > 2 else ''
tar.extract(member, path)
like image 29
ekhumoro Avatar answered Sep 28 '22 05:09

ekhumoro