first, second, etc line of text file

Mike msurel at comcast.net
Thu Jul 26 09:42:26 EDT 2007


On Jul 26, 8:46 am, "Daniel Nogradi" <nogr... at gmail.com> wrote:
> > > A very simple question: I currently use a cumbersome-looking way of
> > > getting the first, second, etc. line of a text file:
>
> > > for i, line in enumerate( open( textfile ) ):
> > >     if i == 0:
> > >         print 'First line is: ' + line
> > >     elif i == 1:
> > >         print 'Second line is: ' + line
> > >     .......
> > >     .......
>
> > > I thought about f = open( textfile ) and then f[0], f[1], etc but that
> > > throws a TypeError: 'file' object is unsubscriptable.
>
> > > Is there a simpler way?
>
> > If all you need is sequential access, you can use the next() method of
> > the file object:
>
> > nextline = open(textfile).next
> > print 'First line is: %r' % nextline()
> > print 'Second line is: %r' % nextline()
> > ...
>
> > For random access, the easiest way is to slurp all the file in a list
> > using file.readlines().
>
> Thanks! This looks the best, I only need the first couple of lines
> sequentially so don't need to read in the whole file ever.

if you only ever need the first few lines of a file, why not keep it
simple and do something like this?

mylines = open("c:\\myfile.txt","r").readlines()[:5]

that will give you the first five lines of the file. Replace 5 with
whatever number you need. next will work, too, obviously, but won't
that use of next hold the file open until you are done with it? Or,
more specifically, since you do not have a file object at all, won't
you have to wait until the function goes out of scope to release the
file? Would that be a problem? Or am I just being paranoid?




More information about the Python-list mailing list