Looping through File Question
planetmatt at gmail.com
Wed Sep 5 14:26:35 CEST 2007
On 5 Sep, 12:34, John Machin <sjmac... at lexicon.net> wrote:
> 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:
> 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:
Thanks so much for the quick response. All working now.
I had looked at the CSV module but when I ran into another problem of
trying to loop through all columns, I was given a solution in another
forum which used the readlines() method.
I have looked at the CSV documentation but didn't see any mention of
heading_row or data_row. Is there a definitive Python documentation
site with code examples like MS's MSDN?
More information about the Python-list