first, second, etc line of text file

Jeff McNeil jeff at jmcneil.net
Wed Jul 25 16:13:49 EDT 2007


Depending on the size of your file, you can just use file.readlines.
Note that file.readlines is going to read the entire file into memory,
so don't use it on your plain-text version of War and Peace.

>>> f = open("/etc/passwd")
>>> lines = f.readlines()
>>> lines[5]
'# lookupd DirectoryServices  \n'
>>>

You can also check out the fileinput module. That ought to be sightly
more efficient and provides some additional functionality.  I think
there are some restrictions on accessing lines out of order, though.

-Jeff

On 7/25/07, Daniel Nogradi <nogradi 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?
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list