diff --git a/Lib/tempfile.py b/Lib/tempfile.py index b5a15f7b72c872..cc4ff8ec27b522 100644 --- a/Lib/tempfile.py +++ b/Lib/tempfile.py @@ -849,9 +849,9 @@ def write(self, s): def writelines(self, iterable): file = self._file - rv = file.writelines(iterable) - self._check(file) - return rv + for line in iterable: + file.write(line) + self._check(file) def detach(self): return self._file.detach() diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2024-11-29-00-59-48.gh-issue-127371.S9Zvnc.rst b/Misc/NEWS.d/next/Core_and_Builtins/2024-11-29-00-59-48.gh-issue-127371.S9Zvnc.rst new file mode 100644 index 00000000000000..5f6c78492d39b1 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2024-11-29-00-59-48.gh-issue-127371.S9Zvnc.rst @@ -0,0 +1 @@ +The ``writelines()`` method in ``SpooledTemporaryFile`` previously only checked whether to roll over to a disk-backed file after the entire iterable was written. This led to high memory usage when handling large iterators, as the in-memory buffer grew without limit. The method was modified to write each line individually and check the buffer size after each write. If the maximum size is exceeded, the file rolls over to disk immediately, preventing excessive memory consumption.