first, second, etc line of text file

Steve Holden steve at holdenweb.com
Thu Jul 26 12:32:16 EDT 2007


Mike wrote:
> 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?
> 
Unfortunately the expression

     f.readlines()[:5]

reads the whole file in and generates a list of the lines just so it can 
slice the first five off. Compare that, on a large file, with something like

     [f.next() for _ in range(5)]

and I think you will see that the latter is significantly better in 
almost all respects.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------




More information about the Python-list mailing list