How to create and read a tar file
Creating a TAR File
File Modes for Python's tarfile Module
Mode | Description |
---|---|
r | Opens a TAR file for reading. |
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. |
# w w w .j ava 2 s . c o m
import os
import tarfile
#Create Tar file
tFile = tarfile.open("files.tar", 'w')
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()
Extracting a File from a TAR File
import os# from w w w .ja v a 2 s . c o m
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()