Add files from one tar into another tar in python

回眸只為那壹抹淺笑 提交于 2019-12-10 13:38:08

问题


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()

回答1:


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

newtar.addfile(member, oldtar.extractfile(member.name))


来源:https://stackoverflow.com/questions/17616340/add-files-from-one-tar-into-another-tar-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!