How to ignore the first line of the text read from a file

rurpy at yahoo.com rurpy at yahoo.com
Thu Aug 28 09:56:34 EDT 2008


On Aug 27, 11:12 pm, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote:
> On Wed, 27 Aug 2008 21:11:26 -0700, youngjin.mich... at gmail.com wrote:
> > I want to read text line-by-line from a text file, but want to ignore
> > only the first line. I know how to do it in Java (Java has been my
> > primary language for the last couple of years) and following is what I
> > have in Python, but I don't like it and want to learn the better way of
> > doing it.
>
> > file = open(fileName, 'r')
> > lineNumber = 0
> > for line in file:
> >     if lineNumber == 0:
> >         lineNumber = lineNumber + 1
> >     else:
> >         lineNumber = lineNumber + 1
> >         print line
>
> > Can anyone show me the better of doing this kind of task?
>
> input_file = open(filename)
> lines = iter(input_file)
> lines.next()    # Skip line.
> for line in lines:
>     print line
> input_file.close()
>
> Ciao,
>         Marc 'BlackJack' Rintsch

A file object is its own iterator so you can
do more simply:

input_file = open(filename)
input_file.next()    # Skip line.
for line in input_file:
    print line,
input_file.close()

Since the line read includes the terminating
EOL character(s), print it with a "print ... ,"
to avoid adding an additional EOL.

If the OP needs line numbers elsewhere in the
code something like the following would work.

infile = open(fileName, 'r')
for lineNumber, line in enumerate (infile):
    # enumerate returns numbers starting with 0.
    if lineNumber == 0: continue
    print line,



More information about the Python-list mailing list