(no subject)


Fri Mar 4 11:35:02 EST 2005


#! rnews 2494
Newsgroups: comp.lang.python
Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!wns13feed!worldnet.att.net!12.120.4.37!attcg2!ip.att.net!xyzzy!nntp
From: Jeff Sandys <sandysj at juno.com>
Subject: Re: Delete first line from file
X-Nntp-Posting-Host: e515855.nw.nos.boeing.com
Content-Type: text/plain; charset=iso-8859-1
Message-ID: <422889BB.1C5DA334 at juno.com>
Sender: nntp at news.boeing.com (Boeing NNTP News Access)
Content-Transfer-Encoding: 8bit
Organization: juno
X-Accept-Language: en
References: <d01n3e$c61$1 at news.uit.no>
Mime-Version: 1.0
Date: Fri, 4 Mar 2005 16:15:55 GMT
X-Mailer: Mozilla 4.79 [en]C-CCK-MCD Boeing Kit  (Windows NT 5.0; U)
Xref: news.xs4all.nl comp.lang.python:365744
Lines: 71

Here is a non-destructive way keeping track of the 
current file position when closing the file and 
re-open the file where you left off.  You can 
always use seek(0) to go back to the beginning.

# ---------------------- start of myfile class
class myfile(file):
    myfiles = {}
    def __init__(self, fname, *args):
        file.__init__(self, fname, *args)
        if self.name in myfile.myfiles:
            pos = myfile.myfiles[fname]
        else:
            pos = 0
        return self.seek(pos)
    def close(self):
        myfile.myfiles[self.name] = self.tell()
        file.close(self)
# ------------------------ end of myfile class

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 at 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'
>>> 

This turned out really cool,
thanks for the good question,
Jeff Sandys


"Tor Erik Sønvisen" wrote:
> 
> Hi
> 
> How can I read the first line of a file and then delete this line, so that
> line 2 is line 1 on next read?
> 
> regards



More information about the Python-list mailing list