File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -597,9 +597,24 @@ def tell(self):
597597 return self .raw .tell ()
598598
599599 def truncate (self , pos = None ):
600+ # On Windows, the truncate operation changes the current position
601+ # to the end of the file, which may leave us with desynchronized
602+ # buffers.
603+ # Since we promise that truncate() won't change the current position,
604+ # the easiest thing is to capture current pos now and seek back to
605+ # it at the end.
606+
607+ initialpos = self .tell ()
600608 if pos is None :
601- pos = self .tell ()
602- return self .raw .truncate (pos )
609+ pos = initialpos
610+
611+ # Flush the stream. We're mixing buffered I/O with lower-level I/O,
612+ # and a flush may be necessary to synch both views of the current
613+ # file state.
614+ self .flush ()
615+ newpos = self .raw .truncate (pos )
616+ self .seek (initialpos )
617+ return newpos
603618
604619 ### Flush and close ###
605620
Original file line number Diff line number Diff line change @@ -181,12 +181,13 @@ def testSetBufferSize(self):
181181 self .assertEquals (d , s )
182182
183183 def testTruncateOnWindows (self ):
184+ # SF bug <http://www.python.org/sf/801631>
185+ # "file.truncate fault on windows"
186+
184187 os .unlink (TESTFN )
188+ f = open (TESTFN , 'wb' )
185189
186- def bug801631 ():
187- # SF bug <http://www.python.org/sf/801631>
188- # "file.truncate fault on windows"
189- f = open (TESTFN , 'wb' )
190+ try :
190191 f .write (b'12345678901' ) # 11 bytes
191192 f .close ()
192193
@@ -205,10 +206,8 @@ def bug801631():
205206 size = os .path .getsize (TESTFN )
206207 if size != 5 :
207208 self .fail ("File size after ftruncate wrong %d" % size )
208-
209- try :
210- bug801631 ()
211209 finally :
210+ f .close ()
212211 os .unlink (TESTFN )
213212
214213 def testIteration (self ):
You can’t perform that action at this time.
0 commit comments