是否可以使用 Python tar 文件读取并附加到 tar

Is it possible to read from and append to a tar with Python tarfile

我正在尝试读取 tar 文件,识别一些文件,读取它们,然后将新文件写入与 Python 相同的 tar 文件。似乎只有模式为 "r" 时才允许使用 extractfile()。是这样吗?有没有一种方法既可以从内存中的 tar 中提取文件,又可以同时将新文件附加到 tar 中?示例代码如下:

def genEntry(tar, tarinfo, source):
    heading = re.compile(r'#+(\s+)?')
    f = tar.extractfile(tarinfo)
    f.seek(0)
    while True:
        line = f.readline().decode()
        print(line)
        if not line:
            break
        print(line)
        if heading.match(line):
            title = heading.sub('',line).replace('\n','')
            return[tarinfo.name.replace(source,'.'), title]
    return [tarinfo.name.replace(source,'.'), tarinfo.name.replace(source,'')]

with tarfile.open(args.source, mode='a') as tar:
  source = 'somepath'
  subDir = 'someSubDir'
  path = '/'.join((source, subDir))
  if tar.getmember(path):
    pathre = re.compile(r'{}\/.+?\/readme\.md'.format(re.escape(path)), re.IGNORECASE)
      for tarinfo in tar.getmembers():
        if re.search(pathre, tarinfo.name):
          genEntry(tar, tarinfo, source)
...

这将产生以下错误:

OSError: bad operation for mode 'a'

据我所知,一次读取和追加一个 tarfile 是不可能的。虽然我最终朝着促进 tarfile 流入和流出我的 Python 脚本的方向发展,但我确实为我的上述问题确定了一个两次通过 read/write 的解决方案。

这基本上是我采用的方法。

    files = []
    with tarfile.open(tarpath) as tar:
        files= readTar(tar)
    with tarfile.open(tarpath, mode='a') as tar:
        for fileobj in files:
            writeFile(tar, fileobj[0], fileobj[1])

def readTar(tar):
# Your your logic to build the files you want to build in the amended file here

def writeFile(tar, tarinfo, payload):
    if len(payload) != 0:
        data = payload.encode('utf8')
        tarinfo.mode = 0o444
        tarinfo.size = len(data)
        tar.addfile(tarinfo, fileobj=BytesIO(data))
        return tar