diff --git a/Lib/io.py b/Lib/io.py index 07846bfb83f..b201cb2bb2b 100644 --- a/Lib/io.py +++ b/Lib/io.py @@ -597,9 +597,24 @@ def tell(self): return self.raw.tell() def truncate(self, pos=None): + # On Windows, the truncate operation changes the current position + # to the end of the file, which may leave us with desynchronized + # buffers. + # Since we promise that truncate() won't change the current position, + # the easiest thing is to capture current pos now and seek back to + # it at the end. + + initialpos = self.tell() if pos is None: - pos = self.tell() - return self.raw.truncate(pos) + pos = initialpos + + # Flush the stream. We're mixing buffered I/O with lower-level I/O, + # and a flush may be necessary to synch both views of the current + # file state. + self.flush() + newpos = self.raw.truncate(pos) + self.seek(initialpos) + return newpos ### Flush and close ### diff --git a/Lib/test/test_file.py b/Lib/test/test_file.py index f2718b2274f..ab29932e8f8 100644 --- a/Lib/test/test_file.py +++ b/Lib/test/test_file.py @@ -181,12 +181,13 @@ def testSetBufferSize(self): self.assertEquals(d, s) def testTruncateOnWindows(self): - os.unlink(TESTFN) + # SF bug + # "file.truncate fault on windows" - def bug801631(): - # SF bug - # "file.truncate fault on windows" - f = open(TESTFN, 'wb') + os.unlink(TESTFN) + f = open(TESTFN, 'wb') + + try: f.write(b'12345678901') # 11 bytes f.close() @@ -205,10 +206,8 @@ def bug801631(): size = os.path.getsize(TESTFN) if size != 5: self.fail("File size after ftruncate wrong %d" % size) - - try: - bug801631() finally: + f.close() os.unlink(TESTFN) def testIteration(self):