diff --git a/Lib/gzip.py b/Lib/gzip.py index 247efc01527bb1..976837826b0fea 100644 --- a/Lib/gzip.py +++ b/Lib/gzip.py @@ -456,12 +456,11 @@ def seek(self, offset, whence=io.SEEK_SET): for i in range(count // self._buffer_size): self.write(chunk) self.write(b'\0' * (count % self._buffer_size)) + return offset elif self.mode == READ: self._check_not_closed() return self._buffer.seek(offset, whence) - return self.offset - def readline(self, size=-1): self._check_not_closed() return self._buffer.readline(size) diff --git a/Lib/test/test_gzip.py b/Lib/test/test_gzip.py index 8bc8e507683cb5..30838f0d00b612 100644 --- a/Lib/test/test_gzip.py +++ b/Lib/test/test_gzip.py @@ -317,9 +317,24 @@ def test_seek_write(self): # Try seek, write test with gzip.GzipFile(self.filename, 'w') as f: for pos in range(0, 256, 16): - f.seek(pos) + self.assertEqual(f.seek(pos), pos) f.write(b'GZ\n') + def test_seek_write_return_value(self): + for whence in (io.SEEK_SET, io.SEEK_CUR): + for padding in (16, gzip._WRITE_BUFFER_SIZE + 16): + with self.subTest(whence=whence, padding=padding): + data = io.BytesIO() + with gzip.GzipFile(fileobj=data, mode='wb') as f: + f.write(b'header') + position = len(b'header') + padding + offset = position if whence == io.SEEK_SET else padding + self.assertEqual(f.seek(offset, whence), position) + f.write(b'record') + self.assertEqual(f.tell(), position + len(b'record')) + self.assertEqual(gzip.decompress(data.getvalue()), + b'header' + b'\0' * padding + b'record') + def test_mode(self): self.test_write() with gzip.GzipFile(self.filename, 'r') as f: diff --git a/Misc/NEWS.d/next/Library/2026-10-21-19-29-18.gh-issue-160071.nG4pTs.rst b/Misc/NEWS.d/next/Library/2026-10-21-19-29-18.gh-issue-160071.nG4pTs.rst new file mode 100644 index 00000000000000..31f212a5603124 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-10-21-19-29-18.gh-issue-160071.nG4pTs.rst @@ -0,0 +1,2 @@ +Fix :class:`gzip.GzipFile` returning a stale position from ``seek()`` when +forward seeking in write mode leaves zero padding in the write buffer.