Bug report
Bug description:
Presumably the "a" TarFile mode was implemented to support both reading and writing, e.g. as evidenced by this line in its __init__() method, if not exactly by its documentation:
modes = {"r": "rb", "a": "r+b", "w": "wb", "x": "xb"}
However, when you try an extractfile() in this mode, you would get an OSError: bad operation for mode 'a' due to the use of self._check("r"). Other extraction functions seem to be doing the same. As such, there seems to be no way to open a TAR file for both reading and writing.
Reproducer
from io import BytesIO
from tarfile import TarFile, TarInfo
with TarFile("test.tar", mode="w") as tar:
contents = b"CONTENTS1"
tarinfo = TarInfo("file1.txt")
tarinfo.size = len(contents)
tar.addfile(tarinfo, BytesIO(contents))
with TarFile("test.tar", mode="r") as tar:
tar.extractfile("file1.txt").read()
with TarFile("test.tar", mode="a") as tar:
contents = b"CONTENTS2"
tarinfo = TarInfo("file2.txt")
tarinfo.size = len(contents)
tar.addfile(tarinfo, BytesIO(contents))
tar.extractfile("file1.txt").read()
Expecting no output from executing this, but getting:
Traceback (most recent call last):
File "<python-input-0>", line 18, in <module>
tar.extractfile("file1.txt").read()
~~~~~~~~~~~~~~~^^^^^^^^^^^^^
File "/usr/local/lib/python3.15/tarfile.py", line 2580, in extractfile
self._check("r")
~~~~~~~~~~~^^^^^
File "/usr/local/lib/python3.15/tarfile.py", line 2969, in _check
raise OSError("bad operation for mode %r" % self.mode)
OSError: bad operation for mode 'a'
CPython versions tested on:
3.15
Operating systems tested on:
Linux
Bug report
Bug description:
Presumably the
"a"TarFilemode was implemented to support both reading and writing, e.g. as evidenced by this line in its__init__()method, if not exactly by its documentation:However, when you try an
extractfile()in this mode, you would get anOSError: bad operation for mode 'a'due to the use ofself._check("r"). Other extraction functions seem to be doing the same. As such, there seems to be no way to open a TAR file for both reading and writing.Reproducer
Expecting no output from executing this, but getting:
CPython versions tested on:
3.15
Operating systems tested on:
Linux