[Q] How to ignore the first line of the text read from a file
norseman
norseman at hughes.net
Thu Aug 28 13:16:45 EDT 2008
Benjamin Kaplan wrote:
> On Thu, Aug 28, 2008 at 12:11 AM, youngjin.michael at gmail.com <
> youngjin.michael at gmail.com> wrote:
>
>> Hello,
>>
>> I am new to Python and have one simple question to which I cannot find
>> a satisfactory solution.
>> 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?
>>
>> Thanks in advance.
>>
>> --
>
>
> Files are iterators, and iterators can only go through the object once. Just
> call next() before going in the for loop. Also, don't use "file" as a
> variable name. It covers up the built-in type.
>
> afile = open(file_name, 'r')
> afile.next() #just reads the first line and doesn't do anything with it
> for line in afile :
> print line
>
>
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
> ------------------------------------------------------------------------
>
> --
> http://mail.python.org/mailman/listinfo/python-list
==================
actually:
import os
file = open(filename, 'r')
for line in file:
dummy=line
for line in file:
print line
is cleaner and faster.
If you need line numbers, pre-parse things, whatever, add where needed.
Steve
norseman at hughes.net
More information about the Python-list
mailing list