How can I skip the header in Python?
Question:
This is my code. I am trying to
-
import the data from net
-
Skip 12 lines
-
Store the rest of the data in a variable and perform some simple operations.
import urllib2
airtemp = urllib2.urlopen('http://coastwatch.glerl.noaa.gov/ftp/glsea/avgtemps/2013/glsea-temps2013_1024.dat').read(30000)
airtemp = airtemp.split("n")
lineskip1 = 0
for line in airtemp:
if lineskip1 <12:
continue
print line
lineskip1+=1
But I’m not able to print the lines.
Answers:
You are continuing the loop without incrementing lineskip1
, so the condition is always true.
lineskip1 = 0
for line in airtemp:
lineskip1 += 1
if lineskip1 <= 12: # Skip lines numbered 1 through 12
continue
print line
A better method is to use enumerate
to count the lines for you.
for i, line in enumerate(airtemp):
if i < 12: # Skip lines numbered 0 through 11
continue
print line
or to use itertools.islice
:
from itertools import islice
for line in islice(airtemp, 12, None): # Skip lines numbered 0 through 11
print line
I think a simple list slice will work:
for line in airtemp[12:]: # start at line 13
print line
This is my code. I am trying to
-
import the data from net
-
Skip 12 lines
-
Store the rest of the data in a variable and perform some simple operations.
import urllib2 airtemp = urllib2.urlopen('http://coastwatch.glerl.noaa.gov/ftp/glsea/avgtemps/2013/glsea-temps2013_1024.dat').read(30000) airtemp = airtemp.split("n") lineskip1 = 0 for line in airtemp: if lineskip1 <12: continue print line lineskip1+=1
But I’m not able to print the lines.
You are continuing the loop without incrementing lineskip1
, so the condition is always true.
lineskip1 = 0
for line in airtemp:
lineskip1 += 1
if lineskip1 <= 12: # Skip lines numbered 1 through 12
continue
print line
A better method is to use enumerate
to count the lines for you.
for i, line in enumerate(airtemp):
if i < 12: # Skip lines numbered 0 through 11
continue
print line
or to use itertools.islice
:
from itertools import islice
for line in islice(airtemp, 12, None): # Skip lines numbered 0 through 11
print line
I think a simple list slice will work:
for line in airtemp[12:]: # start at line 13
print line