Skip to content

Commit e5bc490

Browse files
author
antoine.pitrou
committed
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. git-svn-id: http://svn.python.org/projects/python/trunk@68835 6015fed2-1504-0410-9fe1-9d1591cc4771
1 parent 781e6f3 commit e5bc490

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

Lib/test/test_io.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,17 @@ def test_with_open(self):
232232
else:
233233
self.fail("1/0 didn't raise an exception")
234234

235+
# issue 5008
236+
def test_append_mode_tell(self):
237+
with io.open(test_support.TESTFN, "wb") as f:
238+
f.write(b"xxx")
239+
with io.open(test_support.TESTFN, "ab", buffering=0) as f:
240+
self.assertEqual(f.tell(), 3)
241+
with io.open(test_support.TESTFN, "ab") as f:
242+
self.assertEqual(f.tell(), 3)
243+
with io.open(test_support.TESTFN, "a") as f:
244+
self.assert_(f.tell() > 0)
245+
235246
def test_destructor(self):
236247
record = []
237248
class MyFileIO(io.FileIO):

Misc/NEWS

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,11 @@ Core and Builtins
145145
Library
146146
-------
147147

148+
- Issue #5008: When a file is opened in append mode with the new IO library,
149+
do an explicit seek to the end of file (so that e.g. tell() returns the
150+
file size rather than 0). This is consistent with the behaviour of the
151+
traditional 2.x file object.
152+
148153
- Issue #5013: Fixed a bug in FileHandler which occurred when the delay
149154
parameter was set.
150155

Modules/_fileio.c

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,9 @@ PyTypeObject PyFileIO_Type;
4141

4242
#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
4343

44+
static PyObject *
45+
portable_lseek(int fd, PyObject *posobj, int whence);
46+
4447
/* Returns 0 on success, errno (which is < 0) on failure. */
4548
static int
4649
internal_close(PyFileIOObject *self)
@@ -296,6 +299,16 @@ fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
296299
goto error;
297300
}
298301

302+
if (append) {
303+
/* For consistent behaviour, we explicitly seek to the
304+
end of file (otherwise, it might be done only on the
305+
first write()). */
306+
PyObject *pos = portable_lseek(self->fd, NULL, 2);
307+
if (pos == NULL)
308+
goto error;
309+
Py_DECREF(pos);
310+
}
311+
299312
goto done;
300313

301314
error:

0 commit comments

Comments
 (0)