Untar Archive In Python With Errors
I download a bz2 file using Python. Then I want to unpack the archive using: def unpack_file(dir, file): cwd = os.getcwd() os.chdir(dir) print 'Unpacking file %s' % fil
Solution 1:
For the record, python standard library ships with the tarfile module which automatically handles tar, tar.bz2, and tar.gz formats.
Additionally, you can do nifty things like get file lists, extract subsets of files or directories or chunk the archive so that you process it in a streaming form (i.e. you don't have to decompress the whole file then untar it.. it does everything in small chunks)
import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall()
tar.close()
Solution 2:
I would do it like this:
import tarfile
target_folder = '.'with tarfile.open("sample.tar.gz") as tar:
tar.extractall(target_folder)
That's it. tar
/ with
takes care of the rest.
When you want to have the path to all the files:
importosfilepaths= []
for (dirpath, dirnames, filenames) in walk(target_folder):
filepaths.extend([os.path.join(dirpath, f) for f in filenames])
Post a Comment for "Untar Archive In Python With Errors"