diff --git a/Lib/tarfile.py b/Lib/tarfile.py index c0f5a609b9f42f3..90afd36bb303ce5 100644 --- a/Lib/tarfile.py +++ b/Lib/tarfile.py @@ -2088,6 +2088,7 @@ def close(self): blocks, remainder = divmod(self.offset, RECORDSIZE) if remainder > 0: self.fileobj.write(NUL * (RECORDSIZE - remainder)) + self.offset += (RECORDSIZE - remainder) finally: if not self._extfileobj: self.fileobj.close() diff --git a/Lib/test/test_tarfile.py b/Lib/test/test_tarfile.py index 2d9649237a9382b..84bf00576701cb1 100644 --- a/Lib/test/test_tarfile.py +++ b/Lib/test/test_tarfile.py @@ -1358,6 +1358,17 @@ def test_eof_marker(self): with self.open(tmpname, "rb") as fobj: self.assertEqual(len(fobj.read()), tarfile.RECORDSIZE * 2) + def test_offset_on_close(self): + # Check the offset after calling close matches the total number of + # bytes written. + tar = tarfile.open(tmpname, self.mode) + t = tarfile.TarInfo("foo") + tar.addfile(t) + tar.close() + + with self.open(tmpname, "rb") as fobj: + self.assertEqual(len(fobj.read()), tar.offset) + class WriteTest(WriteTestBase, unittest.TestCase): diff --git a/Misc/NEWS.d/next/Library/2025-05-12-09-59-49.gh-issue-129255._bZvNr.rst b/Misc/NEWS.d/next/Library/2025-05-12-09-59-49.gh-issue-129255._bZvNr.rst new file mode 100644 index 000000000000000..1dd516026390096 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-05-12-09-59-49.gh-issue-129255._bZvNr.rst @@ -0,0 +1 @@ +Update the ``offset`` with the remainder when closing a :func:`tarfile.TarFile`.