Showing posts with label extractall. Show all posts
Showing posts with label extractall. Show all posts

Tuesday, October 27, 2009

Python - extract a tar.gz archive

# extract a tar.gz file with the tarfile module
import tarfile
 
# open the tarfile and use the 'r:gz' parameter
# the 'r:gz' mode enables gzip compression reading
tfile = tarfile.open("archive.tar.gz", 'r:gz')
 
# 99.9% of the time you just want to extract all
# the contents of the archive.
tfile.extractall('.')
 
# Maybe this isn't so amazing for you types out
# there using *nix, os x, or (anything other than
# windows that comes with tar and gunzip scripts).
# However, if you find yourself on windows and
# need to extract a tar.gz you're in for quite the
# freeware/spyware/spamware gauntlet.
 
# Python has everything you need built in!
# Hooray for python!
print "Done!"
 

Monday, October 26, 2009

Python - extract or unzip a tar file

# untar a tar file with python
# python can open, inspect contents, and extract
#   tar files with the built-in
#   tarfile module.
import tarfile
 
# tar file to extract
theTarFile = 'example.tar'
 
# tar file path to extract
extractTarPath = '.'
 
# open the tar file
tfile = tarfile.open(theTarFile)
 
if tarfile.is_tarfile(theTarFile):
    # list all contents
    print "tar file contents:"
    print tfile.list(verbose=False)
    # extract all contents
    tfile.extractall(extractTarPath)
else:
    print theTarFile + " is not a tarfile."
 

Wednesday, September 16, 2009

Python - view contents of and extract files from a ZIP file

import zipfile

# this assumes that the file

#   is in the working directory  
zfileloc = 'breakout.zip'

a = zipfile.ZipFile(zfileloc)

for f in a.infolist():
   print "filename: " + f.filename
   print "compressed size: " + str(f.compress_size)
   print "actual file size:" + str(f.file_size)
   print ""


#output:
#    filename: breakout/
#
#    compressed size: 0
#
#    actual file size:0
#
#

#    filename: breakout/README
#
#    compressed size: 276
#
#    actual file size:443
#
#
#    filename: breakout/LICENSE
#

#    compressed size: 12119
#
#    actual file size:35147
#
#
#    filename: breakout/Blip_1-Surround-147.wav
#
#    compressed size: 9323
#

#    actual file size:9964
#
#
#    filename: breakout/ball.png
#
#    compressed size: 637
#
#    actual file size:642
#

#
#    filename: breakout/breakout.py
#
#    compressed size: 2445
#
#    actual file size:9117
#
#
#    filename: breakout/bat.png

#
#    compressed size: 181
#
#    actual file size:190
#
#
#    filename: breakout/brick.png
#
#    compressed size: 686

#
#    actual file size:686


# extract all contents

a.extractall()


# proof that they were extracted

import os
os.listdir('.')



#output
# the contents of the working directory..... in this example..
# ['breakout.zip', 'breakout']