0

I have this piece of code:

with io.open('csus.csv',mode='r',encoding='latin1') as csus:
  for line in csus:

And I need to ignore the first (header)line. Of course I can work with a virgin boolean, check it's value during the run of the for loop, when False digest the line and set it to False otherwise. But I was hoping to read the first line from the file(handle?) and continue with the for loop

csus.readline()

does not have the expected effect, is it possible and what should I use?

As as a side question should I close the csus file? I don't think this was done in the example I copied it from and I wonder wether this with .. as .. statement already incorporates the close()?

dr jerry
  • 9,768
  • 24
  • 79
  • 122

3 Answers3

2

You can do this with:

with io.open('csus.csv',mode='r',encoding='latin1') as csus:
    next(csus)
    for line in csus:
        # do something

The with statement takes care of closing the file for you.

Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75
  • This is the only one that doesn't run some sort of branch for each line of code – Ben Apr 03 '18 at 18:59
0

Try this:

enumerate and skip the first line

import io
with io.open('csus.csv',mode='r') as csus:
  for i, row in enumerate(csus):
      if(i==0):
          pass
      else:
        print(str(i) + " " + row)
Morse
  • 8,258
  • 7
  • 39
  • 64
0

You can easily achieve it with below code:

with open('any.txt', 'r') as f:
    for i, line in enumerate(f):
        if i > 0:
            print(line) # Change to line.strip() to get rid of new line after everyline
Mick_
  • 131
  • 9