Pythonic love
sohcahtoa82 at gmail.com
sohcahtoa82 at gmail.com
Mon Mar 7 18:03:42 EST 2016
On Monday, March 7, 2016 at 2:51:50 PM UTC-8, 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)
I'd read all the lines at once and then just slice the list.
with open(prfile, mode="rt", encoding="utf-8") as pfile:
lines = pfile.readlines()[5:]
for line in lines:
allVals = line.strip().split("\t")
print(allVals)
Obviously, this will only work well if your file is a reasonable size, as it will store the entire thing in memory at once.
On a side note, your "with open..." line uses inconsistent quoting. You have "" on one string, but '' on another.
More information about the Python-list
mailing list