deleting from tarfile

Mark McEahern marklists at mceahern.com
Sat Jan 15 19:02:33 EST 2005


Uwe Mayer wrote:

>Hi,
>
>is it possible to delete a file from a tar-archive using the tarfile module?
>
>Thanks
>Uwe 
>  
>
It doesn't appear so.  A workaround, of course, is to create a new file 
with the subset of files from the old file:

#!/usr/bin/env python

import tarfile
import os

def removeFile(filename, nameToDelete):
    """Remove nameToDelete from tarfile filename."""
    prefix, ext = os.path.splitext(filename)
    newFilename = '%(prefix)s-modified%(ext)s' % locals()
    original = tarfile.open(filename)
    modified = tarfile.open(newFilename, 'w')
    for info in original.getmembers():
        if info.name == nameToDelete:
            continue
        extracted = original.extractfile(info)
        if not extracted:
            continue
        modified.addfile(info, extracted)
    original.close()
    modified.close()

// m



More information about the Python-list mailing list