Python: Extract using tarfile but ignoring directories Python: Extract using tarfile but ignoring directories python python

Python: Extract using tarfile but ignoring directories


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

import os, tarfileoutput_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 


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, tarfileargs = 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)


As per the tarfile module, you can do that easily.I haven't checked it out yet.

TarFile.extract(member, path="")

Documentation:

Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. member may be a filename or a TarInfo object. You can specify a different directory using path.

So you should be able to do

TarFile.extract(member, path=".")

See the full documentation at : http://docs.python.org/library/tarfile.html