Creating a TAR File


tFile = tarfile.open("files.tar", 'w') files = os.listdir(".") for f in files:     tFile.add(f)

The tarfile module, included with Python, provides a set of easy-to-use methods to create and manipulate TAR files. The open(filename [, mode [, fileobj [, bufsize]]]) method must be called with the write mode set to create a new TAR. Table 4.2 shows the different modes available when opening a TAR file.

Table 4.2. File Modes for Python's tarfile Module

Mode

Description

r

(Default) Opens a TAR file for reading. If the file is compressed, it will be decompressed.

r:

Opens a TAR file for reading with no compression.

w or w:

Opens a TAR file for writing with no compression.

a or a:

Opens a TAR file for appending with no compression.

r:gz

Opens a TAR file for reading with gzip compression.

w:gz

Opens a TAR file for writing with gzip compression.

r:bz2

Opens a TAR file for reading with bzip2 compression.

w:bz2

Opens a TAR file for writing with bzip2 compression.


Once the TAR file has been opened in write mode, files can be added to it using the add(name [,arcname [, recursive]]) method. The add method adds the file or directory specified in name to the archive. The optional arcname argument enables you to specify what name the file should have inside the archive. The recursive argument accepts a Boolean true or false to determine whether or not to recursively add the contents of directories to the archive.

Note

To open a TAR file for sequential access only, replace the : character in the mode with a | character. The append mode is not available for the sequential access option.


import os import tarfile #Create Tar file tFile = tarfile.open("files.tar", 'w') #Add directory contents to tar file files = os.listdir(".") for f in files:     tFile.add(f) #List files in tar for f in tFile.getnames():     print "Added %s" % f tFile.close()


tar_file.py

Added add_zip.py Added del_tree.py Added dir_tree.py Added extract.txt Added extract_tar.py Added file_lines.py Added find_file.py Added get_zip.py Added input.txt Added open_file.py Added output.old Added read_file.py Added read_line.py Added read_words.py Added ren_file.py Added tar_file.py Added write_file.py


Output from tar_file.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