在python中将一个tar中的文件添加到另一个tar中 [英] Add files from one tar into another tar in python
问题描述
我想制作一个 tar 的副本,并删除一些文件(基于它们的名称和可能的其他属性,如符号链接等).由于我已经在 python 中打开了 tar 文件,所以我想在 python 中执行此操作.我知道 TarFile.getmembers() 返回一个 TarInfo 对象列表,而 TarFile.addfile(tarinfo) 接受一个 TarInfo 对象.但是当我将一个输入另一个时,会创建一个损坏的焦油(没有错误).
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()
推荐答案
您必须将 fileobj
-argument 传递给 addfile()
:
You have to pass the fileobj
-argument to addfile()
:
newtar.addfile(member, oldtar.extractfile(member.name))
这篇关于在python中将一个tar中的文件添加到另一个tar中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!