This question was asked on the comp.lang.python newsgroup:

My first response was:

Then I replied with this code snip which worked rather well once I figured out file.close(self) was the way to pass the close() over-ride up to the parent file definition:

code

class myfile(file):
    """remembers the position a file was closed at
       and reopens the file at that position"""
    myfiles = {}
    def __init__(self, fname, *args):
        file.__init__(self, fname, *args)
        if self.name in myfile.myfiles:
            pos = myfile.myfiles[self.name]
        else:
            pos = 0
        return self.seek(pos)
    def close(self):
        myfile.myfiles[self.name] = self.tell()
        file.close(self)

Below is an example with a simple four line file.

PythonWin 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32.
Portions Copyright 1994-2001 Mark Hammond (mhammond@skippinet.com.au) - see 'Help/About PythonWin' for further copyright information.
>>> f = open("C:/Pydev/test.txt")
>>> f.readlines()
['line one\n', 'line two\n', 'line three\n', 'last line\n']
>>> ### short four line file
>>> f.close()
>>> from myfile import myfile
>>> f = myfile("C:/Pydev/test.txt")
>>> f.readline()
'line one\n'
>>> f.readline()
'line two\n'
>>> f.close()
>>> ### test, is the file really closed?
>>> f.readline()
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
ValueError: I/O operation on closed file
>>> f = myfile("C:/Pydev/test.txt")
>>> f.readline()
'line three\n'
>>> ### reopened file starts where it left off
>>> f.readline()
'last line\n'
>>> f.close()
>>> f = myfile("C:/Pydev/test.txt")
>>> f.seek(0)
>>> ### return to the beginning of the file
>>> f.readline()
'line one\n'
>>>

comments on the code

FilePosition (last edited 2008-03-04 08:33:03 by localhost)