Creating a TAR File
The tarfile module, included with Python, provides a set of easy-to-use
Table 4.2. File Modes for Python's tarfile Module
Once the TAR file has been opened in write mode, files can be added to it using the
add
(
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 |
Extracting a File from a TAR File
The tarfile module includes the
exTRact
(file [,
The example in
extract_tar.py
opens the TAR file created in the previous phrase and
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 |