diff -r 4fb829f8c04d Lib/tempfile.py --- a/Lib/tempfile.py Wed Mar 18 11:29:47 2015 +0100 +++ b/Lib/tempfile.py Thu Mar 19 13:18:44 2015 +0100 @@ -426,7 +426,9 @@ # iter() doesn't use __getattr__ to find the __iter__ method def __iter__(self): - return iter(self.file) + # don't return iter(self.file), but yield from it to avoid closing + # file as long as it's being used as iterator, see issue #23000 + yield from iter(self.file) def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, diff -r 4fb829f8c04d Lib/test/test_tempfile.py --- a/Lib/test/test_tempfile.py Wed Mar 18 11:29:47 2015 +0100 +++ b/Lib/test/test_tempfile.py Thu Mar 19 13:18:44 2015 +0100 @@ -707,6 +707,18 @@ # No reference cycle was created. self.assertIsNone(wr()) + def test_iter(self): + # getting iterator from a temporary file should keep it alive + # as long as it's being iterated over + lines = [b'spam\n', b'eggs\n', b'beans\n'] + def make_file(): + f = tempfile.NamedTemporaryFile(mode='w+b') + f.write(b''.join(lines)) + f.seek(0) + return iter(f) + for i, l in enumerate(make_file()): + self.assertEqual(l, lines[i]) + def test_creates_named(self): # NamedTemporaryFile creates files with names f = tempfile.NamedTemporaryFile()