Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add files from one tar into another tar in python

Tags:

python

tar

I would like to make a copy of a tar, with some files removed (based on their name and possably other properties like symlink or so). As I already have the tar file open in python, so I would like to do this in python. I understood that TarFile.getmembers() returns a list of TarInfo objects and TarFile.addfile(tarinfo) accepts a TarInfo object. But when I feed one into the other, a corrupted tar is created (without errors).

import tarfile

oldtar=tarfile.open('/tmp/old.tar',"r")
newtar=tarfile.open('/tmp/new.tar',"w")
for member in oldtar.getmembers():
    if not member.name == 'dev/removeme.txt':
        newtar.addfile(member)
    else:
        print "Skipped", member.name
newtar.close()
oldtar.close()
like image 780
user2576471 Avatar asked Jul 12 '13 13:07

user2576471


1 Answers

You have to pass the fileobj-argument to addfile():

newtar.addfile(member, oldtar.extractfile(member.name))
like image 112
sloth Avatar answered Sep 30 '22 04:09

sloth