Extracting a File from a TAR File


tFile = tarfile.open("files.tar", 'r') tFile.extract(f, extractPath)

The tarfile module includes the exTRact(file [, path]) method to extract files specified by the file argument and place them in the location specified by the path argument. If no path is specified, the current working directory becomes the destination.

The example in extract_tar.py opens the TAR file created in the previous phrase and extracts only the Python files to a directory called /bin/py.

import os import tarfile extractPath = "/bin/py" #Open Tar file tFile = tarfile.open("files.tar", 'r') #Extract py files in tar for f in tFile.getnames():     if f.endswith("py"):         print "Extracting %s" % f         tFile.extract(f, extractPath)     else:         print "%s is not a Python file." % f tFile.close()


extract_tar.py

Extracting add_zip.py Extracting del_tree.py Extracting dir_tree.py extract.txt is not a Python file. Extracting extract_tar.py Extracting file_lines.py Extracting find_file.py Extracting get_zip.py input.txt is not a Python file. Extracting open_file.py output.old is not a Python file. Extracting read_file.py Extracting read_line.py Extracting read_words.py Extracting ren_file.py Extracting tar_file.py Extracting write_file.py


Output from extract_tar.py code




Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net