The tarfile module provides read and write access to Unix tar archives, including compressed files. In addition to the POSIX standards, several GNU tar extensions are supported. Unix special file types such as hard and soft links, and device nodes are also handled.
In [4]:
import tarfile
for filename in ['zlib_server.py', 'example.tar',
'tarfile.ipynb', 'notthere.tar']:
try:
print('{:>15} {}'.format(filename, tarfile.is_tarfile(
filename)))
except IOError as err:
print('{:>15} {}'.format(filename, err))
In [5]:
import tarfile
with tarfile.open('example.tar', 'r') as t:
print(t.getnames())
In [6]:
import tarfile
import time
with tarfile.open('example.tar', 'r') as t:
for member_info in t.getmembers():
print(member_info.name)
print(' Modified:', time.ctime(member_info.mtime))
print(' Mode :', oct(member_info.mode))
print(' Type :', member_info.type)
print(' Size :', member_info.size, 'bytes')
print()
In [8]:
import tarfile
import time
with tarfile.open('example.tar', 'r') as t:
for filename in ['zlib_server.py', 'notthere.txt']:
try:
info = t.getmember(filename)
except KeyError:
print('ERROR: Did not find {} in tar archive'.format(
filename))
else:
print('{} is {:d} bytes'.format(
info.name, info.size))
In [9]:
import tarfile
print('creating archive')
with tarfile.open('tarfile_add.tar', mode='w') as out:
print('add zlib_server.py')
out.add('zlib_server.py')
print()
print('Contents:')
with tarfile.open('tarfile_add.tar', mode='r') as t:
for member_info in t.getmembers():
print(member_info.name)
In [12]:
import tarfile
print('creating archive')
with tarfile.open('tarfile_append.tar', mode='w') as out:
out.add('gzip.ipynb')
print('contents:',)
with tarfile.open('tarfile_append.tar', mode='r') as t:
print([m.name for m in t.getmembers()])
print('adding index.rst')
with tarfile.open('tarfile_append.tar', mode='a') as out:
out.add('zlib.ipynb')
print('contents:',)
with tarfile.open('tarfile_append.tar', mode='r') as t:
print([m.name for m in t.getmembers()])