Pythonic love

jmp jeanmichel at sequans.com
Tue Mar 8 08:25:03 EST 2016


On 03/07/2016 11:51 PM, 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)

what about a generator expression ? The (not so)new hype:

with open(prfile,mode="rt",encoding='utf-8') as pfile:
   for values in (l.strip().split("\t") for (i, l) in enumerate(pfile) 
if i >=5):
     print values

slightly dense, could be better with a lambda function

tovalues = lambda l: l.strip().split("\t")
with open(prfile,mode="rt",encoding='utf-8') as pfile:
   for values in (tovalues(l) for (i, l) in enumerate(pfile) if i >=5):
     print values


This should even work quite efficiently on big files, because I don't 
thing no more than one line is in memory at a given time.

jm







More information about the Python-list mailing list