Pythonic love

Mark Lawrence breamoreboy at yahoo.co.uk
Mon Mar 7 18:19:08 EST 2016


On 07/03/2016 22:51, Fillmore wrote:
>
> learning Python from Perl here. Want to do things as Pythonicly as
> possible.
>
> I am reading a TSV, but need to skip the first 5 lines. The following
> works, but wonder if there's a more pythonc way to do things. Thanks
>
> ctr = 0
> with open(prfile,mode="rt",encoding='utf-8') as pfile:
>      for line in pfile:
>          ctr += 1
>
>          if ctr < 5:
>              continue
>
>          allVals = line.strip().split("\t")
>          print(allVals)

Something like this, completely untested.

with open(prfile,mode="rt",encoding='utf-8') as pfile:
     lineIter = iter(pfile)
     for _ in range(5):
         next(lineIter)
     for line in lineIter:
          allVals = line.strip().split("\t")
          print(allVals)

I'd also recommend that you use the csv module 
https://docs.python.org/3/library/csv.html which can also cope with tsv 
files, it's far more reliable than relying on a simple call to split().

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence




More information about the Python-list mailing list