[Tutor] File Access

Nick Lunt nick at javacat.f2s.com
Mon Apr 5 13:08:05 EDT 2004


Hi Lloyd,

thanks for the info. However, f.seek(0,2) takes me to the end of the
file as you say, but what I need is the whole last line of the file.

After doing f.seek(0,2) successive f.seek(-1, 1) calls will walk me
backwards through the file but to make this useful I would need to keep
checking the current character for an "\n". And unfortunately calls to
f.read() and f.readline() take me back to the end of the file or line
respectively.

Im on linux and the fseek(3) manpage seems to indicate that I cannot
take a file of unknown size and seek to the start of the last line,
would be nice if it did tho ;)

Am I talking rubbish or do you agree ?

Thanks again,
Nick.


On Mon, 2004-04-05 at 03:13, Lloyd Kvam wrote:
> files (file objects) support the seek method:
> 	f.seek(pos,how)
> pos is the position
> how is 0 for start
> 	1 for current location
> 	2 for end
> f.seek(0,2) would place you at the end of the file.
> 
> Note that text mode in Windows can confuse things.  binary mode and unix
> will work as you expect.
> 
> On Sun, 2004-04-04 at 13:26, Nick Lunt wrote:
> > Hi folks,
> > 
> > I need to go to the last line of a file and then to the start of a
> > delimited section of that line, such as
> > 
> > $ cat file.txt
> > var1|var2|var3|var4|var5|var6|var7
> > var1|var2|var3|var4|var5|var6
> > var1|var2|var3|var4|var5|var6
> > 
> > What I want to do is goto the last line in the imaginary file.txt above
> > and extract var3 for example.
> > 
> > I could probably do a realines() until EOF overwriting a variable with
> > the contents of each line so that at the end the variable will hold the
> > contents of just the last line, or by putting each line of the file into
> > a list and pulling the last element of the list out, but eventually the
> > file.txt will get pretty big, so I thought of using seek().
> > 
> > However, I could not find on python.org or by googling any way to do
> > this.
> > 
> > So can anyone please give me a hint on the most efficient way to grab
> > the contents of the last line of a large text file please ?
> > 
> > Kind regards,
> > Nick.
> > 
> > 
> > 
> > 
> > 
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor




More information about the Tutor mailing list