Looping through File Question
John Machin
sjmachin at lexicon.net
Wed Sep 5 07:34:07 EDT 2007
On Sep 5, 8:58 pm, planetmatt <planetm... at gmail.com> wrote:
> I am a Python beginner. I am trying to loop through a CSV file which
> I can do. What I want to change though is for the loop to start at
> row 2 in the file thus excluding column headers.
>
> At present I am using this statement to initiate a loop though the
> records:
>
> for line in f.readlines():
>
> How do I start this at row 2?
The quick answer to your literal question is:
for line in f.readlines()[1:]:
or, with extreme loss of elegance, this:
for lino, line in enumerate(f.readlines()):
if not lino:
continue
But readline and readlines are old hat, and you wouldn't want to read
a file of a few million lines into a big list, so a better answer is:
_unused = f.next()
for line in f:
But you did say you were reading a CSV file, and you don't really want
to do your own CSV parsing, even if you think you know how to get it
right, so best is:
import csv
rdr = csv.reader(f)
heading_row = rdr.next()
for data_row in rdr:
HTH,
John
More information about the Python-list
mailing list