[Python-checkins] r68835 - in python/trunk: Lib/test/test_io.py Misc/NEWS Modules/_fileio.c

antoine.pitrou python-checkins at python.org
Wed Jan 21 01:45:37 CET 2009


Author: antoine.pitrou
Date: Wed Jan 21 01:45:36 2009
New Revision: 68835

Log:
Issue #5008: When a file is opened in append mode with the new IO library,
do an explicit seek to the end of file (so that e.g. tell() returns the
file size rather than 0). This is consistent with the behaviour of the
traditional 2.x file object.



Modified:
   python/trunk/Lib/test/test_io.py
   python/trunk/Misc/NEWS
   python/trunk/Modules/_fileio.c

Modified: python/trunk/Lib/test/test_io.py
==============================================================================
--- python/trunk/Lib/test/test_io.py	(original)
+++ python/trunk/Lib/test/test_io.py	Wed Jan 21 01:45:36 2009
@@ -232,6 +232,17 @@
             else:
                 self.fail("1/0 didn't raise an exception")
 
+    # issue 5008
+    def test_append_mode_tell(self):
+        with io.open(test_support.TESTFN, "wb") as f:
+            f.write(b"xxx")
+        with io.open(test_support.TESTFN, "ab", buffering=0) as f:
+            self.assertEqual(f.tell(), 3)
+        with io.open(test_support.TESTFN, "ab") as f:
+            self.assertEqual(f.tell(), 3)
+        with io.open(test_support.TESTFN, "a") as f:
+            self.assert_(f.tell() > 0)
+
     def test_destructor(self):
         record = []
         class MyFileIO(io.FileIO):

Modified: python/trunk/Misc/NEWS
==============================================================================
--- python/trunk/Misc/NEWS	(original)
+++ python/trunk/Misc/NEWS	Wed Jan 21 01:45:36 2009
@@ -145,6 +145,11 @@
 Library
 -------
 
+- Issue #5008: When a file is opened in append mode with the new IO library,
+  do an explicit seek to the end of file (so that e.g. tell() returns the
+  file size rather than 0). This is consistent with the behaviour of the
+  traditional 2.x file object.
+
 - Issue #5013: Fixed a bug in FileHandler which occurred when the delay
   parameter was set.
 

Modified: python/trunk/Modules/_fileio.c
==============================================================================
--- python/trunk/Modules/_fileio.c	(original)
+++ python/trunk/Modules/_fileio.c	Wed Jan 21 01:45:36 2009
@@ -41,6 +41,9 @@
 
 #define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
 
+static PyObject *
+portable_lseek(int fd, PyObject *posobj, int whence);
+
 /* Returns 0 on success, errno (which is < 0) on failure. */
 static int
 internal_close(PyFileIOObject *self)
@@ -296,6 +299,16 @@
 			goto error;
 	}
 
+	if (append) {
+		/* For consistent behaviour, we explicitly seek to the
+		   end of file (otherwise, it might be done only on the
+		   first write()). */
+		PyObject *pos = portable_lseek(self->fd, NULL, 2);
+		if (pos == NULL)
+			goto error;
+		Py_DECREF(pos);
+	}
+
 	goto done;
 
  error:


More information about the Python-checkins mailing list