Skip to content

Python3.9+ throws KeyError when extracting folder with trailing slash #127636

@ovianao

Description

@ovianao

Bug report

Bug description:

Calling extract() on a member of a tar file that is a directory and contains a trailing forward slash in its name in Python3.9+ causes a KeyError, since the member cannot be found due to what appears to be the trimmed slash here:

tarinfo = self._getmember(name.rstrip('/'))

import tarfile

def create_tar(archive_path):
    tar = tarfile.open(archive_path, 'w')
    t = tarfile.TarInfo('./mydir/')
    tar.addfile(t)
    tar.close()

def extract_tar(archive_path, dest):
    tar = None
    try:
        tar = tarfile.open(archive_path)
        for item in tar.getnames():
            tar.extract(item, dest)
    finally:
        if tar is not None:
            tar.close()

archive = '.\\test.tar'
dest = '.'
create_tar(archive)
extract_tar(archive, dest)

Results in:


Traceback (most recent call last):
  File "C:\temp\tar_test\test.py", line 23, in <module>
    extract_tar(archive, dest)
  File "C:\temp\tar_test\test.py", line 15, in extract_tar
    tar.extract(item, dest)
  File "c:\python39\lib\tarfile.py", line 2077, in extract
    tarinfo = self.getmember(member)
  File "c:\python39\lib\tarfile.py", line 1799, in getmember
    raise KeyError("filename %r not found" % name)
KeyError: "filename './mydir/' not found"

CPython versions tested on:

3.9 EDIT also 3.12.8 and 3.13.1.

Operating systems tested on:

Windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions