Search code examples
pythoniofile-read

python ignore first line with io.open


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()?


Solution

  • 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.